Presentation is loading. Please wait.

Presentation is loading. Please wait.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Chapter 10 Inheritance and Polymorphism.

Similar presentations


Presentation on theme: "Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Chapter 10 Inheritance and Polymorphism."— Presentation transcript:

1 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Chapter 10 Inheritance and Polymorphism 1

2 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 OOP Encapsulation Inheritance Polymorphism 2

3 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Motivations  We can create a class for each shape.  i.e., Circles, Rectangles, Triangles  Many common features  Best class design to avoid redundancy? Inheritance subclass (Circle) can extend base class (Shape) 3

4 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Inheritance The inheritance hierarchy describes a relationship between entities. A poodle is a dog, which is a mammal, which is an animal. A poodle has the same properties as a dog and can do anything a dog can do… 4

5 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Inheritance Syntax: class Subclass extends Superclass { //subclass definition } Subclass inherits the interface of the superclass, and can add to it. 5

6 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Keyword: super To call a superclass constructor To call a superclass method 6 How to access superclass? keyword super refers to the superclass super can be used:

7 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Are superclass’s Constructors Inherited? 7 No. They are not inherited. How to invoke superclass’s constructors?  Explicitly using the super keyword.  Implicitly call the no-arg constructor if it exists. (Otherwise: compilation error)

8 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Superclass’s Constructor Is Always Invoked 8 Subclass’s constructor may invoke any of superclass’s constructors. If none invoked explicitly, super() inserted at beginning.

9 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 CAUTION 9  You must use the keyword super to call the superclass constructor.  Syntax error: Invoking superclass’s constructor by name in subclass.  Call to a superclass constructor must appear first in constructor.

10 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Superclasses and Subclasses 10 GeometricObject1 Circle4 Rectangle1 TestCircleRectangle Run

11 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Constructor Chaining 11 public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } Constructing an instance of a class invokes all the superclasses’ constructors along the inheritance chain. This is called constructor chaining.

12 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Execution 12 public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 1. Start from the main method animation

13 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Execution 13 public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 2. Invoke Faculty constructor animation

14 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Execution 14 public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 3. Invoke Employee’s no- arg constructor animation

15 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Execution 15 public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 4. Invoke Employee(String) constructor animation

16 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Execution 16 public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 5. Invoke Person() constructor animation

17 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Execution 17 public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 6. Execute println animation

18 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Execution 18 public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 7. Execute println animation

19 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Execution 19 public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 8. Execute println animation

20 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Execution 20 public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 9. Execute println animation

21 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Example on the Impact of a Superclass without no-arg Constructor 21 public class Apple extends Fruit { } class Fruit { public Fruit(String name) { System.out.println("Fruit's constructor is invoked"); } Find the errors in the program:

22 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Declaring a Subclass Subclass extends superclass’s properties and methods. It can also: F Add new properties F Add new methods F Override the methods of the superclass 22

23 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Calling Superclass Methods 23 You could rewrite the printCircle() method in the Circle class as follows: public void printCircle() { System.out.println("The circle is created " + super.getDateCreated() + " and the radius is " + radius); }

24 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Overriding Methods in the Superclass 24 Subclass inherits superclass methods. Subclass can modify the implementation of superclass’s method. This is referred to as method overriding. public class Circle extends GeometricObject { // Other methods are omitted /** Override the toString method defined in GeometricObject */ public String toString() { return super.toString() + "\nradius is " + radius; }

25 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 NOTE 25  Accessible instance methods can be overridden.  Private method cannot be overridden  If subclass redefines a method that is private in its superclass, the two methods are completely unrelated.

26 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Overriding vs. Overloading 26

27 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 The Object Class and Its Methods Every class in Java descends from java.lang.Object Default superclass of a class is Object. 27

28 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 The toString() method in Object toString() method returns string representation of the object. Default implementation (class Object) returns object’s type, the at sign (@), and a number representing this object. 28 Loan loan = new Loan(); System.out.println(loan.toString()); Output: Loan@15037e5 Not very informative! Override the toString method …

29 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Object Comparison Comparing Objects: Reference Equality (== operator) vs. Content Equality (equals method) 29

30 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 The equals Method The equals() method compares contents of two objects. Default implementation (in Object): 30 public boolean equals(Object obj) { return (this == obj); } Override to compare contents. public boolean equals(Object o) { if (o instanceof Circle) { return radius == ((Circle)o).radius; } else return false; }

31 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Polymorphism An object of a subtype can be used wherever its supertype value is required. This feature is known as polymorphism. The JVM does not know at compile time what type the variable will refer to. Dynamic binding to locate appropriate method. 31

32 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Dynamic Binding How does dynamic binding work?  Begins with lowest subclass,  Traces up inheritance hierarchy until a method definition is found that matches the method call.  Once an implementation is found, the search stops and the first-found implementation is invoked. 32

33 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Generic Programming With polymorphism, methods can be used generically for many different types of arguments. Hence, the term generic programming. When a method is invoked, the particular implementation is determined dynamically. 33

34 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Generic Programming Example 34 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"; }

35 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Casting Objects We have casted variables of one primitive type to another. Casting can 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 parameter of the Object type. This statement is equivalent to: Object o = new Student(); // Implicit casting m(o); 35 The statement Object o = new Student(), known as implicit casting, is legal because an instance of Student is automatically an instance of Object.

36 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Why Casting Is Necessary? To assign object reference o to variable of Student type: Student b = o; Compilation error! How is this different than Object o = new Student() ? A Student object is always an instance of Object. An Object is not necessarily an instance of Student. You see that o is really a Student object; the compiler can’t. Explicit casting tells the compiler that o is a Student object. Student b = (Student)o; // Explicit casting 36

37 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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. Apple x = (Apple)fruit; Orange y = (Orange)fruit; 37

38 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 The instanceof Operator instanceof operator tests if 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());... } 38

39 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 instanceof Static Type Vs. Dynamic Type Until now an object variable and its reference were always of the same type. 39

40 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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. 40

41 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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. 41 TestPolymorphismCastingRun

42 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 The protected Modifier The protected modifier for data or methods of a class. Protected data or method in public class can be accessed by any class in the same package or its subclasses, even if the subclasses are in a different package. private, default, protected, public 42

43 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Accessibility Summary 43

44 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Visibility Modifiers 44

45 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Subclass Cannot Weaken the Accessibility 45  A subclass may override a protected method in its superclass and change its visibility to public.  A subclass cannot weaken the accessibility of a method defined in the superclass. (A method defined as public in the superclass must be public in the subclass.)

46 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 NOTE 46  Like an instance method, a static method is inherited.  A static method cannot be overridden.  If a static method defined in the superclass is redefined in a subclass, the superclass method is hidden.

47 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Modifiers  Access specifier for overriding method can allow more, but not less, access than the overridden method. (protected can become public, not private)  Compile-time error if attempt to change an instance method in the superclass to a class method in the subclass, and vice versa. 47

48 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Superclass Instance Method Superclass Static Method Subclass Instance Method OverridesCompilation Error Subclass Static MethodCompilation ErrorHides 48 Subclass method with same signature as Superclass's method A subclass can overload a method of its superclass.

49 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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. 49

50 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Immutable Objects and Classes 50 Immutable Object Contents cannot be changed after object is created Its class is an immutable class If you delete the set method in our Circle class, the class would be immutable - radius is private and cannot be changed without a set method. A class with all private data fields and no mutators is not necessarily immutable. (Example: class Student has all private data fields and no mutators, but it is mutable. Look at getBirthDate method!)

51 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Example 51 public class Student { private int id; private BirthDate birthDate; public Student(int ssn, int year, int month, int day) { id = ssn; birthDate = new BirthDate(year, month, day); } public int getId() { return id; } public BirthDate getBirthDate() { return birthDate; } } public class BirthDate { private int year; private int month; private int day; public BirthDate(int newYear, int newMonth, int newDay) { year = newYear; month = newMonth; day = newDay; } public void setYear(int newYear) { year = newYear; } } public class Test { public static void main(String[] args) { Student student = new Student(111223333, 1970, 5, 3); BirthDate date = student.getBirthDate(); date.setYear(2010); // Now the student birth year is changed! } }

52 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 What Class is Immutable? 52 Immutable Class All fields are private No mutators Methods can't be overridden (class or methods are final) If a field isn't primitive or immutable, make a deep clone on the way in and the way out. Example: String class


Download ppt "Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Chapter 10 Inheritance and Polymorphism."

Similar presentations


Ads by Google