1 / 35

Encapsulation Support

Encapsulation Support. Language features for data abstraction Prevent a direct access to instance variables Using private key word instead of public. Example. Public class Attraction { private int minutes; public Attraction() { minutes = 75; }

kalyca
Download Presentation

Encapsulation Support

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Encapsulation Support Language features for data abstraction Prevent a direct access to instance variables Using private key word instead of public

  2. Example Public class Attraction { private int minutes; public Attraction() { minutes = 75; } public Attraction(int d) { minutes = d; } public int getMinutes() { return minutes; } public void setMinutes(int d) { minutes= d; } } • False access : direct instance-variable access from outside x.minutes ,x.minutes=6 : fails to compile • Right access : indirect access via public instance methods x.getMinutes() ,x.setMinutes(6)

  3. Private vs. Public private keyword • Prevent direct instance-variable access (via field-selection operator) • Can still be accessed via public instance methods • Can also be used for instance methods Public interface • Public instance variables and instance methods • Public interfaces are defined first

  4. Data Abstraction and Public Interface • Instance-variable evaluations and assignments through instance methods isolate you from the details of class implementation • Private instance variables force all instance-variable evaluations and assignments to go through instance methods in the public interface, ensuring that you practice data abstraction

  5. Class Inheritance Tie together related classes in hierarchies Define classes that inherit instance variables and methods from other classes

  6. Class Inheritance Example: common variables/methods in Movie and Symphony classes • Movie class : script, actiong, directing, minutes instance variables, rating() instance method, constructors,getMinutes() and setMinutes() • Symphony class : music, playing, conducting, minutes instance variables, rating() instance method, constructors, getMinutes() and setMinutes() • minutes, getMinutes(), and setMinutes() are exact duplicates • Duplication makes software development/maintenance difficult

  7. Solution Using class hierarchy and inheritance • Define minutes, getMinutes(), and setMinutes() in a new class called Attraction alone • Make Movie and Symphony subclasses of Attraction • Movie and Symphony automatically inherit minutes, getMinutes() , and setMinutes() from Attraction without having to duplicate them

  8. Inheritance Sub class-superclass relationship • All instance variables and instance methods in superclass(es) are available in subclass Benefits of inheritance • Avoid duplication and simplify maintenance • Reuse already-debugged superclass code • Facilitate using purchased vendor code without sources

  9. Attraction : minutes, getMinutes(), setMinutes() superclass superclass Movie : script, acting, directing, rating() Symphony : music, playing, conducting, rating() superclass JamesbondMovie : rating() How to Inherit Draw a class-hierarchy diagram to distribute variables/methods

  10. Distribution of Instance Variables/Methods Two criteria of placing instance variables and instance methods • No needless duplication of an instance variable/method • Each instance variable/method is useful in all the subclasses of the class where it is defined E.g. • minutes is useful in both Movie and Symphony • rating() is separate because it is different

  11. Superclass Definition public class Attraction { public int minutes; public Attraction() { System.out.println("Calling Zero-parameter Attraction constructor"); minutes = 75; } public int getMinutes() { return minutes; } public void setMinutes(int d) { minutes =d; } }

  12. Subclass Definition Specifying a class's superclass : using keyword extends public class Movie extends Attraction { public int script, acting, directing; public Movie() { System.out.println("Calling zero-parameter Movie constructor"); script = 5; acting= 5; directing = 5; } public Movie(int s, int a, int d) { script = s; acting= a; directing = d; } public int rating() { return script + acting + directing; } }

  13. Subclass Definition ( cont. ) public class Symphony extends Attraction { public int music, playing, conducting; public Symphony() { System.out.println("Callling zero-parameter Symphony constructor"); music = 5; playing = 5; conducting = 5; } public Symphony(int m, int p, int c) { music = m; playing= p; conducting= c; } public int rating() { return music + playing + conducting; } }

  14. The Object Class If no superclass is specified, the direct superclass is Object class which is located at the top of class hierarchy • Object class defines basic state/behavior that all objects must have • equals(), getClass(), toString(), etc

  15. Constructor Calls in Class Hierarchy When you create an instance of a class (other than the Object class), the zero-parameter constructor in the direct superclass is called first public class Demonstrate { public static void main(String argv[]) { Movie m = new Movie(); Symphony s = new Symphony(); } } -------------Result------------ Calling zero-parameter Attraction constructor Calling zero-parameter Movie constructor Calling zero-parameter Attraction constructor Calling zero-parameter Symphony constructor -----------------------------

  16. Overriding of Methods rating() in JamesBondMovie overrides rating() in Movie public class JamesBondMovie extends Movie { public int rating(){ return 10 + acting +directing; } } public class Demonstrate { public static void main(String argv[]) { Movie x = new Movie(); .....… x.rating(); JameBondMovie y = new JamesBondMovie(); .....… y.rating(); } }

  17. Overriding and Overloading Overriding • Occurs when a subclass method and a superclass method uses the same name and signature • Relationship between a superclass method and a subclass method • Blocks inheritance from the superclass • Subclass method replaces the superclass method • Same method signature and return type

  18. Overriding and Overloading ( cont. ) Overloading • Occurs when two or more methods use the same name yet with different signatures • Relationship between methods available in the same class • Does not block inheritance from the superclass • Separate methods share the same name • Different method signature

  19. Example class A { int draw(int x) { return (x+1); } } class B extends A { int draw(int x, int y) { return (x+y); } } public class C { public static void main (String argv[]) { int i = 2; B x = new B(); System.out.println(x.draw(i)); }/* Both draw(int, int) and draw(int) are */ } /* available in class B */

  20. Polymorphism A subclass instance can be used anywhere that one of its superclass is expected • As the value assigned to a variable • As the argument to a method or constructor • As the object on which a method is invoked public class Demonstrate { public static void main(String argv[]) { Movie x = new JamesBondMovie(); x.rating(); } }

  21. Dynamic Binding When you invoke a method on a reference, the JVM must know which class to use for looking up the method definition • Static binding : use compile-time type of object reference • Dynamic binding : use run-time type of referered-to object C++ makes the distinction based on virtual keyword • Java methods are virtual by default ( dynamic binding ) while C++ functions require virtual to make them overridable Do NOT confuse the dynamic binding with static compilation! ( if rating() were not in Movie class, x.rating() would make a compile bug. )

  22. W X Y Z Single Inheritance Java allows you to specify only one superclass for any class unlike C++ This is to avoid ambiguity problems related to multiple inheritance (e.g, diamond-inheritance) Nothing is wrong with this design because it is legimate The problem is in inheritance of implementations; if W X Y has a variable v, then what does Zref.v refer to? X's copy of v? or Y's copy of v? or a shared copy v?

  23. Abstract Class Abstract class :a class that represents an abstract concept and, as such, should not be instantiated (e.g., food, number, graphic_object, etc) • Use abstract keyword and can only be subclassed public abstract class Attraction { public int minutes; public Attraction() { minutes = 75; } public int getMinutes() { return minutes; } public void setMinutes(int d) { minutes = d; } }

  24. Abstract Class ( cont. ) • Attempt to create an instance of an abstract class fails to compile new Attraction() // fails! • Can declare a variable of abstract class type Attraction x; • Can be an instance of any subclass x = new Movie(); x = new Symphony();

  25. Abstract Method Use of instance method using abstract class variable • Problem : Attraction x; x = new Movie(); x.rating(); // BUG! Cannot be compiled. • One solution : a useless rating method in Attraction just for the sake of compilation for dynamic binding • A better solution : abstract method • Always be shadowed by methods in subclasses • Using keyword abstract and has no body public abstract int rating();

  26. Abstract Method ( cont. ) Can be defined only in abstract class Must define corresponding non-abstract methods in its subclasses public class Demonstrate { public static void main(String argv[]) { Attraction x = new Movie(5, 7, 7); System.out.println("The movie's rating is " + x.rating()); x = new Symphony(7, 5, 5); System.out.println("The symphony's rating is " + x.rating()); } } -------------Result--------------- The movie's rating is 19 The symphony's rating is 17 --------------------------------

  27. Interface Useful when you want to impose the same set of methods on unrelated classes (say, C1, C2, …, Cn) • If the classes are well related, we can declare those methods in their common superclass in the class hierarchy ( if they are not related, the common superclass would be Object class! ) • If multiple inheritance were allowed as in C++, we can make an abstract class A with those abstract methods and make each class Ci a subclass of the abstract class ( or create a new class Ci for each Ci and make it inherit from both A and Ci ). • How can we keep benefits of multiple inheritance without any disadvantages?

  28. An Example : Spreadsheet • Each cell may have an object of class Integer, Dates, Equations, Floats, etc. • They have to implement the same set of methods as a spreadsheet cell (e.g., draw(), toString(), ...) • There will be some methods whose argument type is cell class type and where the methods will be called on behalf of the argument(e.g., foo (cell-class x) { .. x.draw() .. } ) • There is no common superclass except for Object • Creating an abstract class CellValue and creating Integer, Dates, Equations sub classes of it would duplicate too much and be too ugly : Let's inherit declarations only from CellValue

  29. Interface A collection of method definitions without implementations and constant values only (no variables!) • Resembles class declarations : public interface Cellable { public abstract void draw(); ... } • A class implements an interface using a keyword implements and by providing implementations for all its methods public class IntegerCell extends Integer implements Cellable { … public void draw() { code to draw an Integer } … }

  30. Interface ( cont. ) • You can have a method whose parameter is an interface type so that all class instances that implement the interface can be assigned to it static void draw.cell (Cellable x) { x.draw(); } • You cannot instantiate an interface ; must instantiate a class that implements the interface (useless if no classes that implement it) • Interfaces are used for: • Capturing similarities between unrelated classes without forcing a class relationship • Declaring methods that one or more classes are expected to implement

  31. An Example : Java.Util.Enumeration An object that implements Enumeration generates a series of elements (http://java.sun.co m/ products/jdk/1. 1/docs/api/packages. html) e.g., for an object v of a vector class (a growable array) for (Enueration e = v.elements(); e.hasMoreElements(); ) { System.out.println(e.nextElement() ); } e.g., for an object h of a hashtable class for (Enueration e = h.elements(); e.hasMoreElements(); ) { System.out.println(e.nextElement() ); }

  32. An Example : Java.Util.Enumeration ( cont. ) public interface Enumeration { boolean hasMoreElements(); Object nextElement(); } public class Vector { ... public elements() { return new VectorEnumerator(this); } ... } class VectorEnumerator implements Enumeration { Vector vector; int count; VectorEnumerator(Vector v) { vector = v; count = 0; } public boolean hasMoreElements() { return count ! vector.elementCount; } public Object nextElement() { … } }

  33. Interface and Multiple Inheritance Interface do not exactly provide multiple inheritance • Cannot inherit variables from interface • Cannot inherit method implementation from interface • Interface hierarchy is independent of the class hierarchy ( an interface can extend more than one interfaces) Diamond inheritance without multiple inheritance (example) interface W { } interface X extends W { } class Y implements W { } class Z extends Y implements X { }

  34. Interface ( IF ) vs. Abstract Class ( AC ) • AC specifies the full set of methods for an object while IF specifies a subset of methods • AC is useless with subclasses while IF is useless without classes that implement it • Both cannot have instances • A class can have only one direct superclass but it can implement any number of IF • AC ties its subclass to a hierarchy while IF does not • Class specifies full identity ( parentage, role, implementation ) while IF specifies role only

  35. Final Class • Using final keyword makes a class a final class • Cannot be extended, thus can have no subclasses Other use of final • final method cannot be overriden • final variable cannot change its value

More Related