0% found this document useful (0 votes)
10 views49 pages

06 L11 Inheritance

Uploaded by

ahmedhesham43886
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views49 pages

06 L11 Inheritance

Uploaded by

ahmedhesham43886
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Chapter 11: Inheritance and

Polymorphism

CS2: Data Structures and Algorithms


Colorado State University

Original slides by Daniel Liang


Modified slides by Wim Bohm and Sudipto Ghosh

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
1
2

Basic Component: Class


A Class is a software bundle of related states
(properties, or variables) and behaviors
(methods)

✦ State is stored in instance variables


✦ Method exposes behavior

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;

public void setTime(long time){


this.time = time;
}
public void setAlarmTime(long time){
this.alarm_time = time;
}
public long getTime(){return time}
public long getAlarmTime(){return alarm_time}
public void noticeAlarm(){ … //ring alarm }
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
6

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

Example: Inheritance – cont.


Public class SportsWatch extends Clock {
private long start_time;
private long end_time;

public long getDuration()


{
return end_time - start_time;
}

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,

public A() { public A() {


is equivalent to
} super();
}

public A(double d) { public A(double d) {


// some statements is equivalent to
super();
} // some statements
}

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

You must use the keyword super to call the


superclass constructor, instead of the
superclass constructor’s name.
Java requires that the constructor call super
appear first in the constructor.

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");
}
}

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
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");
}
}

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.
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");
}
}

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.
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");
}
}

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);
}
} 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");
}
}

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);
}
}
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");
}
}

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);
}
}
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");
}
}

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);
}
}
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:

public class Apple extends Fruit {


}

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 );
} }
} }

class A exten ds B { class A extend s B {


// T his met hod ove rrides the me thod in B // Th is meth od over loads t he meth od in B
publ ic void p(doub le i) { publi c void p(int i ) {
Sy stem.ou t.print ln(i); Sys tem.out .printl n(i);
} }
} }

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.

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;
}
}

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.

public class Circle { public class Circle extends Object {


... Equivalent
...
} }

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.

Loan loan = new Loan();


System.out.println(loan.toString());

The code displays something like Loan@15037e5 . This


message is not very helpful or informative. Usually you should
override the toString method so that it returns a digestible string
representation of the 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.

A class defines a type. A type defined by a


subclass is called a subtype, and a type defined by
its superclass is called a supertype. Therefore, you
can say that Circle is a subtype of
GeometricObject and GeometricObject is a
supertype for Circle.

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

Since o is an instance of C1, o is also an


Object instance of C2, C3, …, Cn-1, and Cn
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
36
Method Matching vs. Binding
Matching a method signature and binding a method
implementation are two issues. The compiler finds a
matching method according to parameter type, number
of parameters, and order of the parameters at
compilation time (overloading)

A method may be implemented in several subclasses.


The Java Virtual Machine dynamically binds the
implementation of the method at runtime (overriding)

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:

Object o = new Student();


works, while
Student b = o;

Does not, because a Student object is always an instance of Object,


but Object is not in general an instance of Student. For instance,
students have grades, but not all objects. If we know that o IS a
Student, we can cast o:

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:

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());
...
}

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

private, none (if no modifier is used), protected, public

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
44
Accessibility Summary

Modifier Accessed Accessed Accessed Accessed


on members from the from the from a from a different
in a class same class same package subclass package

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;

public class C3 public class C4 public class C5 {


extends C1 { extends C1 { C1 o = new C1();
can access x; can access x; can access o.x;
can access y; can access y; cannot access o.y;
can access z; cannot access z; cannot access o.z;
cannot access u; cannot access u; cannot access o.u;
can invoke m(); can invoke m(); cannot invoke o.m();
} } }

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.

For example, if a method is defined as public


in the superclass, it must be defined as public
in the subclass.

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 {
...
}

✦ The final variable is a constant:


final static double PI = 3.14159;

✦ The final method cannot be


overridden by its subclasses.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
49

You might also like