Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 11 Inheritance and Polymorphism

Similar presentations


Presentation on theme: "Chapter 11 Inheritance and Polymorphism"— Presentation transcript:

1 Chapter 11 Inheritance and Polymorphism
CIS265/506 Cleveland State University – Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition by Y. Daniel Liang

2 Context: Object Oriented Modeling / Programming
Entities in the “real world” Programmers Developers Create classes Abstracting the real world

3 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These geometric classes have many common features. What is the best way to design these classes so to avoid redundancy? The answer is to use object inheritance. 3

4 Example1: Superclasses and Subclasses
4

5 Example1:Superclasses and Subclasses
public abstract class GeometricObject { // Return TRUE is object is filled private String color = "white"; public boolean isFilled() { private boolean filled; return filled; private java.util.Date dateCreated; // Construct a default geometric object // Set filled to either: true/false protected GeometricObject() { public void setFilled(boolean filled) { dateCreated = new java.util.Date(); } // createa obj with color and filled value protected GeometricObject(String color, // Get dateCreated boolean filled) { public java.util.Date getDateCreated() { return dateCreated; this.color = color; this.filled = filled; // Return a string representing this object @Override // Return color public String toString() { public String getColor() { return "created on " return color; + dateCreated + "\ncolor: " + color + " and filled: " + filled; // Set a new color public void setColor(String color) { // Abstract method getArea public abstract double getArea(); // Abstract method getPerimeter public abstract double getPerimeter(); 1 2 2 4 1. Abstract class protected constructor overloaded constructor 2-args 4. abstract methods 5 5

6 Example1: Superclasses and Subclasses
public class Circle4 extends GeometricObject { private double radius = 1; /** Return diameter */ public double getDiameter() { public Circle4() { return 2 * radius; } public Circle4(double radius) { super(); /** Return perimeter */ this.radius = radius; public double getPerimeter() { return 2 * radius * Math.PI; public Circle4(double radius, String color, /* Print the circle info */ boolean filled) { public void printCircle() { super(color, filled); System.out.println(toString() + " Circle created on: " //setColor(color); + getDateCreated() //setFilled(filled); + " and the radius is " + radius); /** Return radius */ @Override public double getRadius() { public String toString() { return radius; return ">>> Circle " + getColor() + "\n" + super.toString() + "\n>>> Radius: " + getRadius() /** Set a new radius */ + " Perimeter: " + getPerimeter() public void setRadius(double radius) { + " Area: " + getArea(); /** Return area */ public double getArea() { return radius * radius * Math.PI; 1 4 2 3 3 5 6

7 Example1: Superclasses and Subclasses
public class Rectangle1 extends GeometricObject { /** Return height */ private double width; public double getHeight() { private double height; return height; public Rectangle1() { } /** Set a new height */ public void setHeight(double height) { public Rectangle1(double width, double height) { super(); this.width = width; /** Return area */ this.height = height; public double getArea() { return width * height; public Rectangle1( double width, double height, /** Return perimeter */ String color, public double getPerimeter() { boolean filled) { return 2 * (width + height); super(color, filled); @Override // setColor(color); public String toString() { // setFilled(filled); return "\n>>> Rectangle " + getColor() // Return width + "\n" + super.toString() public double getWidth() { + "\n>>> Height: " + getHeight() return width; + " Width: " + getWidth() + " Perimeter: " + getPerimeter() // Set a new width + " Area: " + getArea(); public void setWidth(double width) { 2 3 4 3 5 7

8 Example1: Superclasses and Subclasses
Testing GeometricObject1, Circle4 and Rectangle1 Classes public static void main(String[] args) throws FileNotFoundException { // TRY: GeometricObject g1 = new GeometricObject() Circle4 c1 = new Circle4(); System.out.println( c1.toString() ); Rectangle1 r1 = new Rectangle1(); System.out.println( r1.toString() ); Rectangle1 r2 = new Rectangle1(10,20,"Yellow", true); System.out.println( r2.toString() ); } Console >>> Circle white created on Tue Jan 24 17:39:45 EST 2012 color: white and filled: false >>> Radius: 1.0 Perimeter: Area: >>> Rectangle white >>> Height: 0.0 Width: 0.0 Perimeter: 0.0 Area: 0.0 >>> Rectangle Yellow color: Yellow and filled: true >>> Height: 20.0 Width: 10.0 Perimeter: 60.0 Area: 200.0 8

9 Invoking Superclass Constructors
Constructors could be invoked explicitly or implicitly. Explicit calls use the super keyword super() super(arg1, arg2, …) In implicit calls (the keyword super is not used), the superclass no-arg constructor is automatically invoked. If used, the statement super() or super(arguments) must appear in the first line of the subclass constructor. 9

10 Obtaining an Object’s Reference
A convenient user-defined method returning the reference to an object is defined below private String getReference() { return this.getClass().getCanonicalName() + + Integer.toHexString(this.hashCode()); } Example: Reference to a Rectangle object is expressed as Package Class ‘Location’ 10

11 Superclass’s Constructor Is Always Invoked
A constructor may invoke a local overloaded constructor or its superclass’s constructor(s). If none of them is invoked explicitly, the compiler puts super() as the first statement in the constructor. For example, 11

12 Using the Keyword super
The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways: Super-class To call a superclass constructor To call a superclass method super this Sub-class 12

13 Constructor Chaining Creating an instance of a class invokes all the superclasses’ constructors along the inheritance chain. This is called constructor chaining. 13

14 Declaring a Subclass A subclass extends properties and methods from the superclass. You can also: Add new properties Add new methods Override methods of the superclass Super-class Sub-class 14

15 Calling Superclass Methods
You could rewrite the printCircle() method in the Circle4 class as follows: public void printCircle() { System.out.println("The circle is created " + super.getDateCreated() + " and the radius is " + radius); } 1 15

16 Overriding Methods in the Superclass
Sometimes it is necessary for a subclass to modify the implementation of a method defined in its superclass. This is referred to as method overriding. public Class Rectangle1 extends GeometricObject1 { // Other methods are omitted . . . // Override the toString method defined in GeometricObject public String toString() { return "\n>>> Rectangle " + getColor() + "\n" + super.toString() + "\n>>> Height: " + getHeight() + " Width: " + getWidth() + " Perimeter: " + getPerimeter() + " Area: " + getArea(); } . . . 16

17 NOTE An instance method can be overridden only if it is accessible.
A private method cannot be overridden by a subclass because it is not accessible outside its own class. A static method cannot be overridden. 17

18 Overriding vs. Overloading
18

19 The Object Class and Its Methods
Every class in Java is descended from the java.lang.Object class. If no inheritance is specified when a class is defined, the superclass of the class is Object. 19

20 The Object Class and Its Methods
20

21 The toString() method in Object
toString() method returns a string representation of the object. The default implementation returns a string holding: a class name of which the object is an instance, the at and a number (hashcode) representing this object. Loan loan = new Loan(); System.out.println( loan.toString() ); For this example we get something like: You should override the toString method so that it returns a more meaningful string representation of the object. 21

22 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 { public String toString() { return "Grad. Student"; class Student extends Person { return "Student"; class Person extends Object { return "Person"; Polymorphic method m takes parameters of various types. A method that can be applied to values of different types is called a polymorphic function. In our example which implementation of the toString() method is used will be determined dynamically by the Java Virtual Machine at runtime. This capability is known as dynamic binding. Console: Grad. Student Student Person 22

23 Dynamic Binding Suppose an object o is an instance of classes C1, C2, ..., Cn-1, and Cn, where C1 is a subclass of C2, C2 is a subclass of C3, ..., and Cn-1 is a subclass of Cn. Cn is the most general class, and C1 is the most specific class. 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

24 Method Matching The compiler finds a matching method according to:
parameter type, number of parameters, and order of the parameters at compilation time. Example of different invocation of the pay method bill.payWith ( ) bill.payWith ("Visa", " " ); bill.payWith ("two cows" ); 24

25 Casting Objects Casting can 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 obj = new Student(); // implicit casting m(obj); The statement Object obj = new Student(), known as implicit casting, is legal because an instance of Student is automatically an instance of Object. 25

26 Why Casting Is Necessary?
To tell the compiler that an object should be treated as of a particular type you use an explicit casting. In the example below, msg is a block of binary data that could be interpreted in different ways depending on the casting applied on it. Object msg = ChunkOfBinaryData(); Voice v = (Voice) msg; ... Sms s = (Sms) msg; e = ( ) msg; Morse m = (Morse) msg; 26

27 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; float f = ; int n = (int) f; Specializing Observation: Assume fruit is a “banana”. Both castings will fail. The numeric example works. 27

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

29 Example2: Demonstrating Polymorphism and Casting
displayGeometricObject displays the area and diameter if the object is a circle, and displays area if the object is a rectangle. 1 2 3 4 29

30 The equals Method The equals() method compares the contents of two objects object1.equals ( object2 ) The default implementation of the equals method in the Object class is as follows: public boolean equals ( Object otherObject ) { return ( this == otherObject ); } The equals method could be overridden in our Circle example as: public boolean equals ( Object otherObject ) { if (otherObject instanceof Circle) { return this.getRadius() == ((Circle)otherObject).getRadius(); } else return false; 30

31 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. 31

32 Useful Predefined Classes: The ArrayList
Java provides the java.util.ArrayList class that can be used to dynamically store an unlimited number of objects. 32

33 Example3: Using ArrayList 1 of 4
You will get a compilation warning “unchecked operation.” Ignore it for now. public class TestArrayList { public static void main(String[] args) { // Create a list to store cities java.util.ArrayList cityList = new java.util.ArrayList(); // Add some cities in the list cityList.add("London"); // cityList now contains [London] cityList.add("Denver"); // cityList now contains [London, Denver] cityList.add("Paris"); // cityList now contains [London, Denver, Paris] cityList.add("Miami"); // cityList now contains [London, Denver, Paris, Miami] cityList.add("Seoul"); // contains [London, Denver, Paris, Miami, Seoul] cityList.add("Tokyo"); // contains [London, Denver, Paris, Miami, Seoul, Tokyo] 1 London London Denver Paris London Denver Paris Miami Seoul Tokyo 33

34 Example3: Using ArrayList 2 of 4
London Denver Paris Miami Seoul Tokyo System.out.println ( "List size? " + cityList.size() ); // prints 6 System.out.println ( "Is Miami in the list? “ + cityList.contains("Miami") ); // prints true System.out.println ( "The location of Denver in the list? " + cityList.indexOf ("Denver") ); // prints 1 System.out.println ( "Is the list empty? " + cityList.isEmpty()); // prints false 34

35 Example3: Using ArrayList 3 of 4
London Denver Paris Miami Seoul Tokyo // Insert a new city at index 2 cityList.add(2, "Xian"); // Remove a city from the list cityList.remove("Miami"); // Remove a city at index 1 cityList.remove(1); // Display the contents in the list System.out.println ( cityList.toString() ); // print [London, Xian, Paris, Seoul, Tokyo] London Denver Xian Paris Miami Seoul Tokyo London Denver Xian Paris Seoul Tokyo London Xian Paris Seoul Tokyo 35

36 Example3: Using ArrayList 4 of 4
London Xian Paris Seoul Tokyo // Display the contents in the list in reverse order for (int i = cityList.size() - 1; i >= 0; i--) System.out.print( cityList.get(i) + " " ); System.out.println(); // print Tokyo Seoul Paris Xian London // Create a list to store two circles java.util.ArrayList list = new java.util.ArrayList(); // Add two circles list.add ( new Circle4(2) ); list.add ( new Circle4(3) ); // Display the area of the first circle in the list System.out.println ( "The area of the circle? " + ((Circle4)list.get(0)).getArea() ); } abcd1111 abcd2222 36

37 Example4 - A Custom Made Class: MyStack
A stack to hold objects. 37

38 Example4 - A Custom Made Class: MyStack
public class MyStack { private java.util.ArrayList list = new java.util.ArrayList(); public boolean isEmpty() { return list.isEmpty(); } public int getSize() { return list.size(); public Object peek() { return list.get(getSize() - 1); public Object pop() { Object obj = list.get(getSize() - 1); list.remove(getSize() - 1); return obj; public void push(Object obj) { list.add(obj); public int search(Object obj) { return list.lastIndexOf(obj); /** Override the toString in the Object class */ public String toString() { return "stack: " + list.toString(); 38

39 The protected Modifier
The protected modifier can be applied on data and methods in a class. A protected data or method in a 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 (no modifier is used) ⟶ protected ⟶ public Visibility increases 39

40 Accessibility Summary
Modifier on members in a class Accessed from the same class Accessed from the same package Accessed from a subclass Accessed from a different package public Yes protected No default private 40

41 Visibility Modifiers 41

42 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. private ⟶ default (no modifier is used) ⟶ protected ⟶ public Changes of visibility are valid in this direction ⟶ Changes of visibility are invalid in this direction ⟵ 42

43 The final modifier can also be used on local variables in a method.
final NOTE Modifiers (private, public, protected, default) are used on classes, methods, and class variables. The final modifier can also be used on local variables in a method. A final local variable is a constant inside a method. A final class is one that cannot be extended by sub-classing. A final method cannot be overridden by its subclasses. 43

44 Appendix A. Using Eclipse Tool Bar to code a POJO (Plain Old Java Object)
44


Download ppt "Chapter 11 Inheritance and Polymorphism"

Similar presentations


Ads by Google