1 / 50

INF120 Basics in JAVA Programming AUBG, COS dept, Fall semester 2013

INF120 Basics in JAVA Programming AUBG, COS dept, Fall semester 2013 Reference books: Malik D.S. , Java Programming, From Problem Analysis to Program Design, Cengage Learning, 4e 2010 Farrell J. Java Programming, Cengage Learning, 5e 2010

gerry
Download Presentation

INF120 Basics in JAVA Programming AUBG, COS dept, Fall semester 2013

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. INF120Basics in JAVA ProgrammingAUBG, COS dept, Fall semester 2013Reference books:Malik D.S., Java Programming, From Problem Analysis to Program Design, Cengage Learning, 4e 2010 Farrell J. Java Programming, Cengage Learning, 5e 2010 Y.Daniel Liang, Introduction to JAVA Programming, Brief version, Pearson IE, Prentice Hall, 9e 2013Any Java book available in AUBG libraryCourse lecturer: Assoc. Prof. Stoyan Bonev, PhD

  2. INF120 Basics in JAVA Programming AUBG, COS dept, Fall semester 2013 Lecture 23 Title: Polymorphism or Dynamic Binding in Java Reference: MalikFarrell, chap 1, Liang Ch11

  3. Lecture Contents: • To discover polymorphism. • To discover dynamic binding. • To describe casting and explain why explicit downcasting is necessary. • To restrict access to data and methods to subclasses only, using the protected visibility modifier. • To explore the toString(), equals() methods in the Object class. • To prevent class extending and method overriding using the final modifier

  4. Motivations • It is a challenge from one side but gives power and flexibility if you are able to perform different tasks using the same calling statement. What is the way to achieve that effect? The answer is to apply POLYMORPHISM. • How to interpret the term POLYMORPHISM? • Polymorphism (from Greek meaning “many forms” )= • = Giving different meaning to the same thing • = Variable of a super type can refer to a subtype object • In assignment statement or • Through parameter passing mechanism

  5. Sub type and Super type • A class defines a type. • A type defined by a subclass is a subtype. • A type defined by its superclass is a supertype. • For example: • Circle is a subtype of GeometricObject • GeometricObject is a supertype for Circle.

  6. Polymorphism • Inheritance is a relation that enables a sub class to inherit features from its superclass with additional new features. • A subclass is a specialized form of its superclass. • Every instance of a sub class is an instance of a superclass BUT not vice versa. • Example: Every circle is a geometric object, BUT not every geometric object is a circle. • !!! You can always assign an instance of a subclass to a reference variable of its superclass type. • !!! You can always pass an actual argument /instance of a subclass type/ to meet corresponding formal parameter /instance of its superclass type/.

  7. Polymorphism • How was P. presented in COS220? • How is P. in C++? • Early binding and Late binding • With or without reserved word virtual • How is P. in Java? • Dynamic binding instead early/late binding

  8. Consider code in Java // source text file: ProgBaseDerv1Derv2.java given inheritance hierarchy Object | Base / \ Derived1 Derived2 Classes Base, Derived1, Derived2 provide method toString() and method show()

  9. Consider code in Java class Base { public void show() { System.out.println("Base " ); } public String toString() { return "\n\nBase"; } } // end of class Base class Derived1 extends Base { public void show() { System.out.println("Derived1" );} public String toString() { return "\n\nDerived1"; } } // end of class Derived1 class Derived2 extends Base { public void show() { System.out.println("Derived2" );} public String toString() { return "\n\nDerived2"; } } // end of class Derived2

  10. Consider code in Java // source text file: ProgBaseDerv1Derv2.java public class ProgBaseDerv1Derv2 { public static void main(String[] args) { Object o = new Object(); System.out.println(" " + o.toString()); Base a = new Base(); System.out.println(" " + a.toString()); a.show(); Derived1 b = new Derived1(), cir1 = new Derived1(); System.out.println(" " + b.toString()); b.show(); Derived2 c = new Derived2(), rect1 = new Derived2(); System.out.println(" " + c.toString()); c.show(); Object[ ] arr = new Object[4]; arr[0] = o; arr[1] = a; arr[2] = b; arr[3] = c; for(int i=0; i<4; i++) System.out.println( arr[i].toString()); // o is named polymorphic variable o=a; o=b; o=c; a=b; a=c; } // end of method main() } // end of class ProgBaseDerv1Derv2

  11. Comments • Ref variable o is Object type. • Array ref variable arr is Object type. • We can assign any instance of Object ((eg. new Base, new Derived1, or new Derived2 to o or to arr array element • GEN RULE: An object of a subtype can be used wherever its supertype value is required or in other words a ref var of a super class type can point to an object of its sub class type. • This feature is known as polymorphism.

  12. Consider code in Java // source text file: ProgPolymorphismDemo.java given inheritance hierarchy Object | GeometricObject / \ Circle Rectangle

  13. Consider code in Java // source text file: ProgpolymorphismDemo.java public static void main(String args[]) {displayObject(new Circle(1, "red", false)); displayObject(new Rectangle(1, 1, "blue", true)); Circle aa = new Circle(1, "red", false); displayObject(aa); Rectangle bb = new Rectangle(1, 1, "blue", true); displayObject(bb); } // end of main public static void displayObject( GeometricObject o) { System.out.println("Created:"+o.getDateCreated()+“ Color:“ +o.getColor()+" Filled:"+o.isFilled()); // or System.out.println("Created:"+o.dateCreated+" Color:“ +o.color+" Filled:"+o.filled); }

  14. Comments • The formal param is GeometricObject o. • The actual argument may be any instance of GeometricObject (eg. new Circle or new Rectangle) • GEN RULE: An object of a subtype can be used wherever its supertype value is required or in other words a ref var of a super class type (formal param) can point to an object of its sub class type (actual arg). • This feature is known as polymorphism.

  15. Dynamic Binding // file: ProgGeometricObject3.java Object o = new GeometricObject(); System.out.println(o.toString());Object aa = new Circle(1); System.out.println(aa.toString()); Q. Which toString() method is invoked by o and by aa? Before answer, let introduce two terms: declared type actual type

  16. Dynamic Binding Object o = new GeometricObject(); A variable must be declared a type. The type of a variable is called its declared type. o’s declared type is Object. The actual type is the actual class for the object referenced by the variable o’s actual type is GeometricObject Which toString() method is invoked by o is determined by o’s actual type. This is known as dynamic binding

  17. Dynamic Binding Given a hierarchy of classes: C1, C2, ..., Cn-1, Cn, where C1 is a subclass of C2, C2 is a subclass of C3, ..., Cn-1 is a subclass of Cn. That is, Cn is the most general class, and C1 is the most specific class. In Java, Cn is the Object class. Dynamic binding works as follows: Suppose an object o is an instance of class C1. If o invokes a method p, the JVM searches the implementation for the method p in C1, C2, ..., Cn-1 and Cn, in this order, until it is found. Once an implementation is found, the search stops and the first-found implementation is invoked.

  18. class Person extends Object { public String toString() { return "Person"; } } class Student extends Person { public String toString() { return "Student"; } } class GraduateStudent extends Student { } public class PolymorphismDemo { public static void main(String[] args) { m(new GraduateStudent()); m(new Student()); m(new Person()); m(new Object()); } public static void m(Object x) { System.out.println(x.toString()); } } Program output is: Can you analyze? What is the expected result?

  19. class Person extends Object { public String toString() { return "Person"; } } class Student extends Person { public String toString() { return "Student"; } } class GraduateStudent extends Student { } public class PolymorphismDemo { public static void main(String[] args) { m(new GraduateStudent()); m(new Student()); m(new Person()); m(new Object()); } public static void m(Object x) { System.out.println(x.toString()); } } Program output is: Student Student Person Java.lang.Object@16f0472

  20. Polymorphism, Dynamic Binding and Generic Programming public class PolymorphismDemo { public static void main(String[] args) { m(new GraduateStudent()); m(new Student()); m(new Person()); m(new Object()); } public static void m(Object x) { System.out.println(x.toString()); } } class GraduateStudent extends Student { } class Student extends Person { public String toString() { return "Student"; } } class Person extends Object { public String toString() { return "Person"; } } Method m takes a parameter of the Object type. You can invoke it with any object. When the method m(Object x) is executed, the argument x’s toString method is invoked. x may be an instance of GraduateStudent, Student, Person, or Object. Classes GraduateStudent, Student, Person, and Object 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. An object of a subtype can be used wherever its supertype value is required. This feature is known as polymorphism. DynamicBindingDemo Run

  21. Polymorphism and Dynamic Binding, Method m takes a parameter of the Object type. You can invoke it with any object. When the method m(Object x) is executed, the argument x’s toString method is invoked. x may be an instance of GraduateStudent, Student, Person, or Object. Classes GraduateStudent, Student, Person, and Object 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. An object of a subtype can be used wherever its supertype value is required. This feature is known as polymorphism.

  22. Dynamic Binding explained twice Given a hierarchy of classes: C1, C2, ..., Cn-1, Cn, where C1 is a subclass of C2, C2 is a subclass of C3, ..., Cn-1 is a subclass of Cn. That is, Cn is the most general class, and C1 is the most specific class. In Java, Cn is the Object class. Dynamic binding works as follows: Suppose an object o is an instance of class C1. If o invokes a method p, the JVM searches the implementation for the method p in C1, C2, ..., Cn-1 and Cn, in this order, until it is found. Once an implementation is found, the search stops and the first-found implementation is invoked.

  23. Method Matching vs. Binding Matching a method signature and binding a method implementation are two separate issues. The compiler finds a matching method according to parameter type, number of parameters, and order of the parameters at compile time (early, static binding). A method may be implemented in several subclasses. The JVMe dynamically binds the implementation of the method at run time, decided by the actual type of the variable (late, dynamic binding).

  24. Generic Programming public class PolymorphismDemo { public static void main(String[] args) { m(new GraduateStudent()); m(new Student()); m(new Person()); m(new Object()); } public static void m(Object x) { System.out.println(x.toString()); } } class GraduateStudent extends Student { } class Student extends Person { public String toString() { return "Student"; } } class Person extends Object { public String toString() { return "Person"; } } Polymorphism allows methods to be used generically for a wide range of object arguments. This is known as generic programming. If a method’s parameter type is a superclass (e.g., Object), you may pass an object to this method of any of the parameter’s subclasses (e.g., Student or String). When an object (e.g., a Student object or a String object) is used in the method, the particular implementation of the method of the object that is invoked (e.g., toString) is determined dynamically.

  25. Casting Objects You have already used the casting operator to convert variables of one primitive type to another. // casting – convert from int to double double d2; int a2 = 55; d2 = a2; // allowed d2 = (double) a2; // allowed Same approach applied when casting objects

  26. Casting Objects You have already used the casting operator to convert variables of one primitive type to another. // casting – convert from double to int double d1=3.156; int a1; a1 = d1; // compiler error a1 = (int) d1; // allowed Same approach applied when casting objects 26

  27. Casting Objects You have already used the casting operator to convert variables of one primitive type to another. double d1=3.156, d2; int a1, a2=55; // casting – convert from int to double d2 = a2; // allowed d2 = (double) a2; // allowed // casting – convert from double to int a1 = d1; // compiler error a1 = (int) d1; // allowed Same approach applied when casting objects 27

  28. Casting Objects Casting can also be used to convert an object of one class type to another within an inheritance hierarchy. In the preceding section, the statement m(new Student()); assigns the object new Student() to a formal 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.

  29. Why Casting Is Necessary? Suppose you want to assign the object reference o to a variable of the Student type using the following statement: Student b = o; A compilation error would occur. Why does the statement Object o = new Student(); work and the statement Student b = o; doesn’t? This is because a Student object is always an instance of Object, but an Object is not necessarily an instance of Student. Even though you can see that o is really a Student object, the compiler is not so clever to know it. To tell the compiler that o is a Student object, use an explicit casting. The syntax is similar to the one used for casting among primitive data types. Enclose the target object type in parentheses and place it before the object to be cast, as follows: Student b = (Student)o; // Explicit casting

  30. TIP To help understand casting, you may also consider the analogy of fruit, apple, and orange with the Fruit class as the superclass for Apple and Orange. An apple is a fruit, so you can always safely assign an instance of Apple to a variable for Fruit. However, a fruit is not necessarily an apple, so you have to use explicit casting to assign an instance of Fruit to a variable of Apple.

  31. Casting from Superclass to Subclass Explicit casting must be used when casting an object from a superclass to a subclass. This type of casting may not always succeed. // explicit casting only allowed Apple x = (Apple)fruit; Orange x = (Orange)fruit; // implicit casting not allowed Apple x = fruit;

  32. Casting from Subclass to Superclass Explicit or implicit casting must be used when casting an object from a subclass to a superclass. This type of casting may always succeed. Fruit f1, f2; Apple apl = new Apple(); f1 = apl; // implicit casting allowed f2=(Fruit)apl;//explicit casting allow

  33. Casting fromSuperclass to Subclass Explicit casting must be used when casting an object from a superclass to a subclass. This type of casting may not always succeed. Object o = new GeometricObject(); Circle ac = new Circle();ac = o; // syntax error, not every geometric object is //necessarily a circle. ac = (Circle) o; // OK, but casting may not always succeed

  34. Casting from Subclass to Superclass Explicit or implicit casting must be used when casting an object from a subclass to a superclass. This type of casting may always succeed. Object o = new GeometricObject(); Circle ac = new Circle(); o=ac; // always allowed o = (GeometricObject)ac; // always allowed o = (Circle)ac; // always allowed

  35. The instanceof Operator Use the instanceof operator to test whether an object is an instance of a class: Object myObject = new Circle(); ... // Some lines of code /** Perform casting if myObject is an instance of Circle */ if (myObject instanceof Circle) { System.out.println("The circle diameter is " + ((Circle)myObject).getDiameter()); ... }

  36. Example (8e): Demonstrating Polymorphism and Casting // source text file: ProgCastingDemo.java Given: inheritance relation Object - GeometricObject – Circle,Rectangle geometricObject (base class) – Circle, Rectangle (sub classes) Problem: write a program that creates two Object instances initialized as Circle(1.0) object and as a Rectangle(1.,1.0) object, and invokes the displayObject() method to display the objects. The displayObject() displays the area and diameter if the object is a circle, and displays area if the object is a rectangle.

  37. Example: Demonstrating Polymorphism and Casting This example creates two geometric objects: a circle, and a rectangle, invokes the displayGeometricObject method to display the objects. The displayGeometricObject displays the area and diameter if the object is a circle, and displays area if the object is a rectangle. CastingDemo Run

  38. Example (8e): Demonstrating Polymorphism and Casting • Examine the source text: • Q. which is the declared type and which is the actual type of o1 and o2? Object o1 = new Circle(1, "red", false); Object o2 = new Rectangle(1, 1, "blue", true);

  39. Example (8e): Demonstrating Polymorphism and Casting • Examine the source text: • Q. what output is to display after following stmts? System.out.println(" "+ (o1 instanceof Object ) ); System.out.println(" "+ (o1 instanceof GeometricObject) ); System.out.println(" "+ (o1 instanceof Circle ) ); System.out.println(" "+ (o1 instanceof Rectangle ) );

  40. Example (8e): Demonstrating Polymorphism and Casting • Examine the source text: • Q. what output is to display after following stmts? System.out.println(" "+ (o2 instanceof Object ) ); System.out.println(" "+ (o2 instanceof GeometricObject) ); System.out.println(" "+ (o2 instanceof Circle ) ); System.out.println(" "+ (o2 instanceof Rectangle ) );

  41. Example (8e): Demonstrating Polymorphism and Casting • Examine the source text: • A. what output is to display after following stmts? o1 o2 Object true true GeometricObject true true Circle true false Rectangle false true

  42. Example (5e): Demonstrating Polymorphism and Casting // source text file: ProgCastingDemo2.java Given: inheritance relation between circle – cylinder Circle (base class) – Cylinder (sub class) Problem: write a program that creates two objects, a circle and a cylinder, and invokes the displayObject() method to display them. The displayObject() method displays area if the object is circle and volume if the object is cylinder.

  43. The Object class • It is important to be familiar with methods provided by the Object class so that you can use them in your classes. • Some of these methods are: • public boolean equals(Object object) • public int hashCode() • public String toString()

  44. The toString() method in Object ThetoString()method returns a string representation of the object. The default implementation returns a string consisting of a class name of which the object is an instance, the at sign (@), and a number representing this object. Circle circle = new Circle(); System.out.println(circle.toString()); The code displays something like Circle@15037e5.This message is not very helpful or informative. Usually you should override thetoStringmethod so that it returns a digestible string representation of the object.

  45. The toString() method in Object The toString() method returns a string representation of the object. The default implementation returns a string consisting of a class name of which the object is an instance, the at sign (@), and a number representing this object. Loan loan = new Loan(); System.out.println(loan.toString()); The code displays something like Loan@15037e5.This message is not very helpful or informative. Usually you should override the toString method so that it returns a digestible string representation of the object.

  46. Theequals Method The equals() method compares thecontents of two objects. The default implementation of the equals method in the Object class is as follows: public boolean equals(Object obj) { return (this == obj); } Using the equals method is equivalent to the == operator in the object class, BUT it is intended for the subclasses of the Object class to modify (override) theequalsmethod to test whether two distinct objects have the same content

  47. NOTE The == comparison operator is used for comparing two primitive data type values or for determining whether two objects have the same references. The equals() method is intended to test whether two objects have the same contents, provided that the method is modified in the defining class of the objects. The == operator is stronger than the equals() method, in that the == operator checks whether the two reference variables refer to the same object.

  48. The hashCodeMethod • Invoking hashCode() on object returns the object’s hash code. • Hash code is an integer that can be used to store the object in a hash set so that it can be located quickly. • Method hashCode() returns the internal memory address of the object in hex • You should override hashCode() whenever you override equals() method. WHY? If two objects are equal, their hash codes must be the same.

  49. 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 beoverridden by its subclasses.

  50. Thank You For Your Attention! Any Questions?

More Related