Professional Documents
Culture Documents
CSE215-B4-Inheritance and Polymorphism PDF
CSE215-B4-Inheritance and Polymorphism PDF
CSE215-B4-Inheritance and Polymorphism PDF
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 1
rights reserved. 0132130807
Superclasses and Subclasses
GeometricObject
-color: String The color of the object (default: white).
-filled: boolean Indicates whether the object is filled with a color (default: false).
-dateCreated: java.util.Date The date when the object was created.
+GeometricObject() Creates a GeometricObject.
+GeometricObject(color: String, Creates a GeometricObject with the specified color and filled
filled: boolean) values.
GeometricObject1
+getColor(): String Returns the color.
+setColor(color: String): void Sets a new color.
+isFilled(): boolean Returns the filled property.
+setFilled(filled: boolean): void Sets a new filled property.
+getDateCreated(): java.util.Date Returns the dateCreated.
+toString(): String Returns a string representation of this object.
Circle4
Circle Rectangle
Rectangle1
-radius: double -width: double
+Circle() -height: double
+Circle(radius: double) +Rectangle()
+Circle(radius: double, color: String, +Rectangle(width: double, height: double)
filled: boolean) +Rectangle(width: double, height: double
+getRadius(): double
+setRadius(radius: double): void
color: String, filled: boolean)
+getWidth(): double TestCircleRectangle
+getArea(): double +setWidth(width: double): void
+getPerimeter(): double +getHeight(): double
+getDiameter(): double
+printCircle(): void
+setHeight(height: double): void
+getArea(): double Run
+getPerimeter(): double
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 2
rights reserved. 0132130807
Are superclass’s Constructor Inherited?
No. They are not inherited.
They are invoked explicitly or implicitly.
Explicitly using the super keyword.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 4
rights reserved. 0132130807
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:
• To call a superclass constructor
• To call a superclass method
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 5
rights reserved. 0132130807
CAUTION
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 6
rights reserved. 0132130807
Constructor Chaining
Constructing an instance of a class invokes all the superclasses’ constructors along
the inheritance chain. This is called constructor chaining.
public class Faculty extends Employee {
public static void main(String[] args) {
Faculty f1 = 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");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 7
rights reserved. 0132130807
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
Faculty f1 = new Faculty(); 1. Start from the
} main method
public Faculty() {
System.out.println("(4) Faculty'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");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 8
rights reserved. 0132130807
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
Faculty f1 = new Faculty(); 2. Invoke Faculty
} constructor
public Faculty() {
System.out.println("(4) Faculty'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");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 9
rights reserved. 0132130807
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
Faculty f1 = new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
} 3. Invoke Employee’s no-
class Employee extends Person {
arg constructor
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");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 10
rights reserved. 0132130807
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
Faculty f1 = new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
4. Invoke Employee(String)
class Employee extends Person { constructor
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");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 11
rights reserved. 0132130807
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
Faculty f1 = new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
public Employee(String s) {
System.out.println(s);
}
} 5. Invoke Person() constructor
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 12
rights reserved. 0132130807
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
Faculty f1 = new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
public Employee(String s) {
System.out.println(s);
}
}
6. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 13
rights reserved. 0132130807
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
Faculty f1 = new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
public Employee(String s) {
System.out.println(s);
}
}
7. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 14
rights reserved. 0132130807
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
Faculty f1 = new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
public Employee(String s) {
System.out.println(s);
}
}
8. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 15
rights reserved. 0132130807
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
Faculty f1 = new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
9. Execute println
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");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 16
rights reserved. 0132130807
Example on the Impact of a Superclass without
no-arg Constructor
class Fruit {
public Fruit(String name) {
System.out.println("Fruit's constructor is invoked");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 17
rights reserved. 0132130807
Reference variable of a Superclass can refer
to an object of that class and its subclasses.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 18
rights reserved. 0132130807
Declaring a Subclass
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 19
rights reserved. 0132130807
Calling Superclass Methods
You could rewrite the printCircle() method in the Circle class as
follows:
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 20
rights reserved. 0132130807
Overriding Methods in the Subclass
A subclass inherits methods from a superclass. Sometimes it is
necessary for the subclass to modify the implementation of a method
defined in the superclass. This is referred to as method overriding.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 21
rights reserved. 0132130807
NOTE: Instance Method Inheritance
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 22
rights reserved. 0132130807
NOTE: Class/Static Method Inheritance
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 23
rights reserved. 0132130807
Method Overriding and Static Methods
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 24
rights reserved. 0132130807
Static & Instance Methods
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 25
rights reserved. 0132130807
Static & Instance Methods
public class Animal { public class TestDemo {
public static void testStaticMethod() { public static void main(String[] args) {
System.out.println("The static method in Animal"); Cat myCat = new Cat();
} Animal myAnimal = myCat;
public void testInstanceMethod() {
System.out.println("The instance method in Animal"); Animal.testStaticMethod();
} Cat.testStaticMethod();
}
myAnimal.testStaticMethod();
public class Cat extends Animal {
myCat.testStaticMethod();
public static void testStaticMethod() {
System.out.println("The static method in Cat");
myAnimal.testInstanceMethod();
}
myCat.testInstanceMethod();
public void testInstanceMethod() {
}
System.out.println("The instance method in Cat");
}
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 26
rights reserved. 0132130807
NOTE: An instance method cannot override a static method,
and a static method cannot hide an instance method.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 27
rights reserved. 0132130807
Overriding vs. Overloading
In a subclass, we can overload the methods inherited from the superclass.
Such overloaded methods neither hide nor override the superclass
methods — they are new methods, unique to the subclass.
public class Test { public class Test {
public static void main(String[] args) { public static void main(String[] args) {
A a = new A(); A a = new A();
a.p(10); a.p(10);
a.p(10.0); a.p(10.0);
} }
} }
class B { class B {
public void p(double i) { public void p(double i) {
System.out.println(i * 2); System.out.println(i * 2);
} }
} }
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 28
rights reserved. 0132130807
The Object Class and Its Methods
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 29
rights reserved. 0132130807
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 30
rights reserved. 0132130807
Polymorphism, Dynamic Binding and Generic Programming
class Person extends Object {
public String toString() { Method test takes a parameter of the
return "Person";
} Object type. You can invoke it with any
} object.
class Student extends Person {
public String toString() { An object of a subtype can be used
return "Student";
}
wherever its supertype value is
} required. This feature is known as
class GraduateStudent extends Student { polymorphism.
}
When the method test(Object x) is
public class PolymorphismDemo {
public static void main(String[] args) {
executed, the argument x’s toString
Object obj = new GraduateStudent(); method is invoked. x may be an
test(obj); instance of GraduateStudent, Student,
obj = new Student();
test(obj);
Person, or Object. Classes
obj = new Person(); GraduateStudent, Student, Person, and
test(obj); Object have their own implementation
obj = new Object();
test(obj);
of the toString method. Which
} implementation is used will be
determined dynamically by the Java
public static void test(Object x) {
System.out.println(x.toString());
Virtual Machine at runtime. This
} capability is known as dynamic
} binding.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 31
rights reserved. 0132130807
Dynamic Binding
Dynamic binding works as follows: 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. That is,
Cn is the most general class, and C1 is the most specific class. In
Java, Cn is the Object 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.
Cn Cn-1 ..... C2 C1
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 33
rights reserved. 0132130807
Generic Programming
public class PolymorphismDemo {
public static void main(String[] args) {
m(new GraduateStudent());
m(new Student()); Polymorphism allows methods to be used
m(new Person());
m(new Object()); generically for a wide range of object
} arguments. This is known as generic
public static void m(Object x) { programming. If a method’s parameter
System.out.println(x.toString()); type is a superclass (e.g., Object), you
}
} may pass an object to this method of any
class GraduateStudent extends Student {
of the parameter’s subclasses (e.g.,
} Student or String). When an object (e.g.,
class Student extends Person {
a Student object or a String object) is
public String toString() { used in the method, the particular
return "Student"; implementation of the method of the
}
} object that is invoked (e.g., toString) is
class Person extends Object {
determined dynamically.
public String toString() {
return "Person";
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 34
rights reserved. 0132130807
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());
Student b = o;
Apple x = (Apple)fruit;
Orange x = (Orange)fruit;
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 37
rights reserved. 0132130807
Calling a Subclass’s Method Using A Superclass’s Reference
Variable
GeometricObj g1;
g1 = new GeometricObj(“Green”, true);
double a = g1.getArea(); X
// Can’t access using superclass ref var
((Circle)g1).getArea()
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 38
rights reserved. 0132130807
The instanceof Operator
Use the instanceof operator to test whether an object is an
instance of a class:
Explicit casting
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 39
rights reserved. 0132130807
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:
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 40
rights reserved. 0132130807
NOTE
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 41
rights reserved. 0132130807
(Generic Programming) The ArrayList Class
You can create an array to store objects. But the array’s size is fixed
once the array is created. Java provides the ArrayList class that can
be used to store an unlimited number of objects.
java.util.ArrayList
+ArrayList() Creates an empty list.
+add(o: Object) : void Appends a new element o at the end of this list.
+add(index: int, o: Object) : void Adds a new element o at the specified index in this list.
+clear(): void Removes all the elements from this list.
+contains(o: Object): boolean Returns true if this list contains the element o.
+get(index: int) : Object Returns the element from this list at the specified index.
+indexOf(o: Object) : int Returns the index of the first matching element in this list.
+isEmpty(): boolean Returns true if this list contains no elements.
+lastIndexOf(o: Object) : int Returns the index of the last matching element in this list.
+remove(o: Object): boolean Removes the element o from this list.
+size(): int Returns the number of elements in this list.
+remove(index: int) : Object Removes the element at the specified index.
+set(index: int, o: Object) : Object Sets the element at the specified index.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 42
rights reserved. 0132130807
The MyStack Classes
A stack to hold objects.
MyStack
MyStack
-list: ArrayList A list to store elements.
+isEmpty(): boolean Returns true if this stack is empty.
+getSize(): int Returns the number of elements in this stack.
+peek(): Object Returns the top element in this stack.
+pop(): Object Returns and removes the top element in this stack.
+push(o: Object): void Adds a new element to the top of this stack.
+search(o: Object): int Returns the position of the first element in the stack from
the top that matches the specified element.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 43
rights reserved. 0132130807
The protected Modifier
• The protected modifier can be applied on data
and methods in a class. A protected data or a
protected 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, protected, public
Visibility increases
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 44
rights reserved. 0132130807
Accessibility Summary
public
protected -
default - -
private - - -
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 45
rights reserved. 0132130807
Visibility Modifiers
package p1;
public class C1 { public class C2 {
public int x; C1 o = new C1();
protected int y; can access o.x;
int z; can access o.y;
private int u; can access o.z;
cannot access o.u;
protected void m() {
} can invoke o.m();
} }
package p2;
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 46
rights reserved. 0132130807
A Subclass Cannot Weaken the Accessibility
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 47
rights reserved. 0132130807
The final Modifier
• The final class cannot be extended:
final class Math {
...
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 48
rights reserved. 0132130807