06 L11 Inheritance
06 L11 Inheritance
Polymorphism
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
1
2
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
3
Basic Components
✦ Class: Blueprint from which objects are
created
– Multiple Object Instances created from a class
✦ Interface: A Contract between classes and the
outside world.
– When a class implements an interface, it promises
to provide the behavior published by that
interface.
✦ Package: a namespace (directory) for
organizing classes and interfaces
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
4
Data Encapsulation
✦ An ability of an object to be a container (or
capsule) for related properties and methods.
– Preventing unexpected change or reuse of the
content
✦ Data hiding
– Object can shield variables from external access.
◆ Private variables
◆ Public accessor and mutator methods, with potentially
limited capacities, e.g. only read access, or write only
valid data.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
5
Data Encapsulation
public class Clock{
private long time, alarm_time;
Inheritance
✦ The ability of a class to derive properties
and behaviors from a previously defined
class.
✦ Relationship among classes.
✦ Enables reuse of software components
– e.g., java.lang.Object()
– toString(), equals(), etc.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
CS200 - Advanced OO
7
Example: Inheritance
Clock
Sports Radio
Watch Clock
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
CS200 - Advanced OO
8
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
CS200 - Advanced OO
9
Overriding Methods
public class RadioClock extends Clock
{
@override
public void noticeAlarm(){
ring alarm
turn_on_the_Radio
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Another Example
Suppose you want to define classes to model
circles, rectangles, and triangles. These classes
have many common features.
What is the best way to design these classes so to
avoid redundancy?
The answer is to use inheritance: creating a
hierarchy of classes, where common features are
shared in higher level classes.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
10
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.
+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.
Circle Rectangle
-radius: double -width: double
-height: double
+Circle()
+Circle(radius: double) +Rectangle()
+Circle(radius: double, color: String,
filled: boolean)
+Rectangle(width: double, height: double) GeometricObject
+Rectangle(width: double, height: double
+getRadius(): double color: String, filled: boolean)
+setRadius(radius: double): void +getWidth(): double CircleFromSimpleGeometricObject
+getArea(): double +setWidth(width: double): void
+getPerimeter(): double +getHeight(): double RectangleFromSimpleGeometricObject
+getDiameter(): double +setHeight(height: double): void
+printCircle(): void +getArea(): double
+getPerimeter(): double TestCircleRectangle Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
11
Definition: Inheritance
✦ Inheritance:
Lower level classes get (access to)
certain methods and data from higher level
classes
✦ Data and methods are now defined in one
place (the super class) and used in this
and lower (sub) classes
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
12
Are superclass’s Constructor
Inherited?
No. They are not inherited.
They are invoked explicitly or implicitly.
Explicitly using the super keyword.
A constructor is used to construct an instance of a class. Unlike
data and methods, a superclass's constructors are not inherited in
the subclass. They can only be invoked from the subclasses'
constructors, using the keyword super.
If the keyword super is not explicitly used, the superclass's no-arg
constructor is automatically invoked.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
13
Superclass’s Constructor Is Always Invoked
A constructor may invoke an overloaded constructor or its
superclass’s constructor. If none of them is invoked
explicitly, the compiler puts super() as the first statement
in the constructor. For example,
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
14
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
15
CAUTION
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
16
Constructor Chaining
Constructing an instance of a class invokes all the superclasses’ constructors
along the inheritance chain. This is known as constructor chaining.
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");
}
}
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
17
rights reserved.
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
18
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
19
animation
Trace Execution
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");
}
} 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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
20
animation
Trace Execution
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");
}
}
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
21
animation
Trace Execution
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");
}
}
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
22
animation
Trace Execution
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");
}
}
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
23
animation
Trace Execution
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");
}
}
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
24
animation
Trace Execution
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");
}
}
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
25
animation
Trace Execution
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");
}
}
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
26
Example on the Impact of a Superclass
without no-arg Constructor
Error: Fruit has no no-arg constructor, so Apple fails:
class Fruit {
public Fruit(String name) {
System.out.println("Fruit's constructor is invoked");
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
27
Defining a Subclass
A subclass inherits methods and data from a
superclass. You can also:
✦ Add new properties
✦ Add new methods
✦ Override the methods of the superclass
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
28
Overriding vs. Overloading
Overloading occurs when two or more
methods in the same class have the same
method name but different parameters.
Overriding means having two methods with
the same method name and parameters (i.e.,
method signature). One of the methods is in
the parent class and the other is in the child
class.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
29
Overriding vs. Overloading
public class Test { public class T est {
publ ic stat ic void main( String[ ] args) { publi c stati c void main(St ring[] 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 {
publ ic void p(doub le i) { publi c void p(doubl e i) {
Sy stem.ou t.print ln(i * 2); Sys tem.out .printl n(i * 2 );
} }
} }
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
30
Overriding Methods in the Superclass
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
31
NOTE
An instance method can be overridden only
if it is accessible.
Thus a private method cannot be overridden,
because it is not accessible outside its own
class.
If a method defined in a subclass is private
in its superclass, the two methods are
completely unrelated.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
32
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
33
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
34
Polymorphism
Polymorphism means that a variable of a supertype
can refer to a subtype object.
PolymorphismDemo Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
35
Dynamic Binding
Object o is an instance of class C1
C1 is a subclass of C2, C2 is a subclass of C3, ...etc.,
Cn is the Object class.
If a method in 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, and
that method is invoked.
Cn Cn-1 ..... C2 C1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
37
Casting Objects
Casting can be used to convert an object of one class type to another
within an inheritance hierarchy. In the code:
Student b = (Student)o;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
38
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 x = (Orange)fruit;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
39
The instanceof Operator
Use the instanceof operator to test whether an object is an
instance of a class:
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
40
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
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
41
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;
}
public boolean equals(Object o) {
For example, the if (o instanceof Circle) {
equals method is return radius == ((Circle)o).radius;
overridden in }
the Circle else
return false;
class. }
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
42
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
equals method is overriden in the defining class of the
objects.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
43
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
44
Accessibility Summary
public
protected -
default - -
private - - -
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
45
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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
46
Modifier hierarchy
We cannot reduce the visibility / accessibility
of a method.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
47
NOTE
The modifiers are used on classes and
class members (data and methods), except
that the final modifier can also be used on
local variables in a method. A final local
variable is a constant inside a method.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
48
The final Modifier
✦ The final class cannot be extended:
final class Math {
...
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
49