Se ha denunciado esta presentación.
Utilizamos tu perfil de LinkedIn y tus datos de actividad para personalizar los anuncios y mostrarte publicidad más relevante. Puedes cambiar tus preferencias de publicidad en cualquier momento.

8 polymorphism

393 visualizaciones

Publicado el

  • Sé el primero en comentar

  • Sé el primero en recomendar esto

8 polymorphism

  1. 1. Inheritance and Polymorphism Chapter 9 1
  2. 2. Polymorphism, Dynamic Binding and Generic Programmingpublic class Test { public static void main(String[] args) { m(new GraduateStudent()); Method m takes a parameter m(new Student()); m(new Person()); of the Object type. You can m(new Object()); invoke it with any object. } public static void m(Object x) { An object of a subtype can be used wherever its System.out.println(x.toString()); } supertype value is required. This feature is} known as polymorphism.class GraduateStudent extends Student {}class Student extends Person { When the method m(Object x) is executed, the public String toString() { return "Student"; argument x’s toString method is invoked. x } may be an instance of GraduateStudent,} Student, Person, or Object. Classesclass Person extends Object { GraduateStudent, Student, Person, and Object public String toString() { return "Person"; have their own implementation of the toString} } method. Which implementation is used will be determined dynamically by the Java Virtual Machine at runtime. This capability is known as dynamic binding. 2
  3. 3. Dynamic BindingDynamic binding works as follows: Suppose an object o is aninstance of classes C1, C2, ..., Cn-1, and Cn, where C1 is a subclass ofC2, C2 is a subclass of C3, ..., and Cn-1 is a subclass of Cn. That is, Cnis the most general class, and C1 is the most specific class. InJava, Cn is the Object class. If o invokes a method p, the JVMsearches the implementation for the method p in C1, C2, ..., Cn-1 andCn, in this order, until it is found. Once an implementation isfound, the search stops and the first-found implementation isinvoked. Cn Cn-1 ..... C2 C1 Since o is an instance of C1, o is also anObject instance of C2, C3, …, Cn-1, and Cn 3
  4. 4. Method Matching vs. BindingMatching a method signature and binding a methodimplementation are two issues.•Compiler finds a matching method according to parametertype, number of parameters, and order of the parameters atcompilation time. A method may be implemented in severalsubclasses.•Java Virtual Machine dynamically binds the implementation ofthe method at runtime.•See Review Questions 9.7 and 9.8. 4
  5. 5. Generic Programmingpublic class Test { public static void main(String[] args) { Polymorphism allows methods to be used m(new GraduateStudent()); generically for a wide range of object m(new Student()); m(new Person()); arguments. This is known as generic m(new Object()); programming. } If a method’s parameter type is a public static void m(Object x) { superclass (e.g., Object), you may pass an System.out.println(x.toString()); object to this method of any of the } parameter’s subclasses (e.g., Student or} GraduateStudent).class GraduateStudent extends Student { When an object (e.g., a Student object or} a GraduateStudent object) is used in theclass Student extends Person { method, the particular implementation of public String toString() { the method of the object that is invoked } return "Student"; (e.g., toString) is determined dynamically.}class Person extends Object { public String toString() { return "Person"; }} 5
  6. 6. Example• Polymorphism2 project• FindArea project in Polymorphism• FindArea2 project in Polymorphism• Discussion: Why is it neat? 6
  7. 7. Casting ObjectsYou have already used the casting operator to convert variables ofone primitive type to another. Casting can also be used to convert anobject of one class type to another within an inheritance hierarchy. Inthe preceding section, the statement m(new Student());assigns the object new Student() to a parameter of the Object type.This statement is equivalent to: Object o = new Student(); // Implicit casting m(o); The statement Object o = new Student(), known as implicit casting, is legal because an instance of Student is automatically an instance of Object. 7
  8. 8. Why Casting Is Necessary?Suppose you want to assign the object reference o to a variable of theStudent type using the following statement: Object o; Student b = o; // A compilation error would occur.But Object o = new Student(); // compilesReason: A Student object is always an instance of Object, butan Object is not necessarily an instance of Student. Thecompiler is not so clever.Remedy: Use an explicit casting. Student b = (Student)o; // Explicit casting 8
  9. 9. Casting from Superclass to SubclassExplicit casting must be used when castingan object from a superclass to a subclass.This type of casting may not always succeed. Cylinder myCylinder = (Cylinder)myCircle; Apple x = (Apple)fruit; Orange x = (Orange)fruit; 9
  10. 10. The instanceof OperatorDefensive programming:Use the instanceof operator to test whether anobject is an instance of a class. If so, you can cast it:Circle myCircle = new Circle();if (myCircle instanceof Cylinder) { Cylinder myCylinder = (Cylinder)myCircle; ...} 10
  11. 11. TIP: To help understand castingCompare fruit - {apple, orange} withFruit superclass -{Apple , Orange}An apple is a fruit, so assigning an instanceof Apple to a variable for Fruit is safe.However, a fruit is not necessarily an apple,so must use explicit casting to assign aninstance of Fruit to a variable of Apple. 11
  12. 12. Demonstrating Polymorphism and CastingExample:creates two geometric objects: a circle, and a cylinder;invokes the displayGeometricObject method to displaythe objects.The displayGeometricObject displays the area andperimeter if the object is a circle, and displays area andvolume if the object is a cylinder.See BJ_Polymorphism_Casting 12
  13. 13. Other notables 13
  14. 14. A Subclass Cannot Weaken the AccessibilityA subclass may override a protectedmethod in its superclass and change itsvisibility to public. However, a subclasscannot weaken the accessibility of amethod defined in the superclass. Forexample, if a method is defined as publicin the superclass, it must be defined aspublic in the subclass. 14
  15. 15. The final Modifier• The final class cannot be extended: final class Math { ... }• The final variable is a constant: final static double PI = 3.14159;• The final method cannot be overridden by its subclasses. 15
  16. 16. Optional The equals() and hashCode() Methods in the Object Class • The equals() method compares the contents of two objects. • The hashCode() method returns the hash code of the object. Hash code is an integer, which can be used to store the object in a hash set so that it can be located quickly. 16
  17. 17. The equals MethodThe equals() method compares thecontents of two objects. The default implementationof the equals method in the Object class is asfollows: public boolean equals(Object obj) {For example, the public boolean equals(Object o) {equals method is if (o instanceof Circle) {overridden in return radius == ((Circle)o).radius; }the Circle elseclass. return false; } 17
  18. 18. NOTE: == vs equal()The == comparison operator compares•two primitive data type values or•whether two objects have the same references.The equals method tests•whether two objects have the same contents, provided thatthe method is modified in the defining class of the objects.•== operator is stronger than the equals method, in that the== operator checks whether the two reference variables referto the same object. 18
  19. 19. The hashCode() methodobject.hashCode() returns the hash code of the object.Hash code is an integer, which can be used to store the objectin a hash set so that it can be located quickly.Hash sets will be discussed in “Java Collections Framework.”The hashCode implemented in the Object class returns theinternal memory address of the object in hexadecimal.Your class should override the hashCode method wheneverthe equals method is overridden.By contract, if two objects are equal, their hash codes must besame. 19
  20. 20. Optional The finalize, clone, and getClass Methods •The finalize method is invoked by the garbage collector on an object when the object becomes garbage. •The clone() method copies an object. •The getClass() method returns an instance of the java.lang.Class class, which contains the information about the class for the object. You can get the information about the class at runtime. 20
  21. 21. Initialization Block (optional) Initialization blocks can be used to initialize objects along with the constructors. An initialization block is a block of statements enclosed inside a pair of braces. An initialization block appears within the class declaration, but not inside methods or constructors. It is executed as if it were placed at the beginning of every constructor in the class.public class Book { public class Book { private static int numOfObjects; private static int numOfObjects; private String title private String title; private int id; private int id; Equivalent public Book(String title) { public Book(String title) { this.title = title; numOfObjects++; } this.title = title; } public Book(int id) { = id; public Book(int id) { } numOfObjects++; = id; { } numOfObjects++; } }} 21
  22. 22. Initialization Blockpublic class Book { { numOfObjects++; }} 22
  23. 23. Static Initialization BlockA static initialization block is much like anonstatic initialization block except that it isdeclared static, can only refer to staticmembers of the class, and is invoked whenthe class is loaded. The JVM loads a classwhen it is needed. A superclass is loadedbefore its subclasses. 23
  24. 24. Static Initialization Blockclass A extends B {static { System.out.println("As static initialization block " + "is invoked"); }}class B {static { System.out.println("Bs static initialization block " + “is invoked"); }} 24