1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Inheritance and.
Advertisements

1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Lecture 11: Polymorphism and Dynamic Binding Polymorphism Static (compile-time) binding Dynamic (run-time) binding.
UFCE3T-15-M Programming part 1 UFCE3T-15-M Object-oriented Design and Programming Block2: Inheritance, Polymorphism, Abstract Classes and Interfaces Jin.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Inheritance and interfaces A class C1 is derived from class C2, then C1 is called subclass, and C2 is called superclass Superclass-parent, base class Subclass.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Outline §Abstract class and interface §Inner classes and initialization blocks §Equality §Exception §Threads.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 8 Inheritance and Polymorphism 一切皆有缘起.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
OOP: Inheritance. Inheritance A class can extend another class, inheriting all its data members and methods while redefining some of them and/or adding.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
1 Chapter 4 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 11 Inheritance and Polymorphism.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
1 Chapter 2 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Lecture 4: Object Composition, Inheritance and Polymorphism Michael Hsu CSULA.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. P ART 3: A GGREGATION, I NHERITANCE AND P.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved  To develop a subclass from.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Lecture 4: Object Composition, Inheritance and Polymorphism
Chapter 11 Inheritance and Polymorphism
Chapter 11 Inheritance and Polymorphism
Java Primer 1: Types, Classes and Operators
IST311 Advanced Issues in OOP: Inheritance and Polymorphism
IST311 Advanced Issues in OOP: Inheritance and Polymorphism
Continuing Chapter 11 Inheritance and Polymorphism
CS 302 Week 11 Jim Williams, PhD.
Chapter 9 Inheritance and Polymorphism
Extending Classes.
Chapter 9 Inheritance and Polymorphism
Chapter 8 Class Inheritance and Interfaces
Chapter 11 Inheritance and Polymorphism Part 2
Chapter 11 Inheritance and Polymorphism Part 1
Presentation transcript:

1 Inheritance and Polymorphism Chapter 9

2 Polymorphism, Dynamic Binding and Generic Programming public class Test { 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. An object of a subtype can be used wherever its supertype value is required. This feature is known as polymorphism. 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.

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

4 Method Matching vs. Binding Matching a method signature and binding a method implementation are two issues. Compiler finds a matching method according to parameter type, number of parameters, and order of the parameters at compilation time. A method may be implemented in several subclasses. Java Virtual Machine dynamically binds the implementation of the method at runtime. See Review Questions 9.7 and 9.8.

5 Generic Programming public class Test { 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 GraduateStudent). When an object (e.g., a Student object or a GraduateStudent object) is used in the method, the particular implementation of the method of the object that is invoked (e.g., toString) is determined dynamically.

6 Example Polymorphism2 project FindArea project in Polymorphism FindArea2 project in Polymorphism Discussion: Why is it neat?

7 Casting Objects You have already used the casting operator to convert variables of one primitive type to another. 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 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.

8 Why Casting Is Necessary ? Suppose you want to assign the object reference o to a variable of the Student type using the following statement: Object o; Student b = o;// A compilation error would occur. But Object o = new Student(); // compiles Reason: A Student object is always an instance of Object, but an Object is not necessarily an instance of Student. The compiler is not so clever. Remedy: Use an explicit casting. Student b = (Student)o; // Explicit casting

9 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. Cylinder myCylinder = (Cylinder)myCircle; Apple x = (Apple)fruit; Orange x = (Orange)fruit;

10 The instanceof Operator Defensive programming: Use the instanceof operator to test whether an object is an instance of a class. If so, you can cast it: Circle myCircle = new Circle(); if (myCircle instanceof Cylinder) { Cylinder myCylinder = (Cylinder)myCircle;... }

11 TIP: To help understand casting Compare fruit - {apple, orange} with Fruit superclass -{Apple, Orange} An apple is a fruit, so assigning an instance of Apple to a variable for Fruit is safe. However, a fruit is not necessarily an apple, so must use explicit casting to assign an instance of Fruit to a variable of Apple.

12 Demonstrating Polymorphism and Casting Example: creates two geometric objects: a circle, and a cylinder; invokes the displayGeometricObject method to display the objects. The displayGeometricObject displays the area and perimeter if the object is a circle, and displays area and volume if the object is a cylinder. See BJ_Polymorphism_Casting

13 Other notables

14 A Subclass Cannot Weaken the Accessibility A subclass may override a protected method in its superclass and change its visibility to public. However, a subclass cannot weaken the accessibility of a method defined in the superclass. For example, if a method is defined as public in the superclass, it must be defined as public in the subclass.

15 The final Modifier The final class cannot be extended: final class Math {... } The final variable is a constant: final static double PI = ; The final method cannot be overridden by its subclasses.

16 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. Optional

17 The equals Method The equals() method compares the contents 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); } For example, the equals method is overridden in the Circle class. public boolean equals(Object o) { if (o instanceof Circle) { return radius == ((Circle)o).radius; } else return false; }

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 that the 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 refer to the same object.

19 The hashCode() method object.hashCode() 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. Hash sets will be discussed in “ Java Collections Framework. ” The hashCode implemented in the Object class returns the internal memory address of the object in hexadecimal. Your class should override the hashCode method whenever the equals method is overridden. By contract, if two objects are equal, their hash codes must be same.

20 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. Optional

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.

22 Initialization Block public class Book { { numOfObjects++; }

23 Static Initialization Block A static initialization block is much like a nonstatic initialization block except that it is declared static, can only refer to static members of the class, and is invoked when the class is loaded. The JVM loads a class when it is needed. A superclass is loaded before its subclasses.

24 Static Initialization Block class A extends B { static { System.out.println("A's static initialization block " + "is invoked"); } class B { static { System.out.println("B's static initialization block " + “is invoked"); }