You are on page 1of 35

CHAPTER 11 INHERITANCE AND

POLYMORPHISM

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
MOTIVATIONS
Suppose you will 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.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
INTRODUCTION (CONT.)
 Class hierarchy
 Direct superclass
 Inherited explicitly (one level up hierarchy)
 Indirect superclass
 Inherited two or more levels up hierarchy
 Single inheritance
 Inherits from one superclass
 Multiple inheritance
 Inherits from multiple superclasses
 Java does not support multiple inheritance

3 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
SUPERCLASSES AND SUBCLASSES
 Superclasses and subclasses
 Object of one class “is an” object of another class
 Example: Rectangle is quadrilateral.
 Class Rectangle inherits from class Quadrilateral

 Quadrilateral: superclass

 Rectangle: subclass

 Superclass typically represents larger set of objects than


subclasses
 Example:
 superclass: Vehicle

 subclass: Car

 Smaller, more-specific subset of vehicles

4 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Superclass Subclasses
Student GraduateStudent, UndergraduateStudent
Shape Circle, Triangle, Rectangle
Loan CarLoan, HomeImprovementLoan,
MortgageLoan
Employee Faculty, Staff
BankAccount CheckingAccount, SavingsAccount

FIG. 9.1 | INHERITANCE EXAMPLES.

5 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
SUPERCLASSES AND SUBCLASSES
(CONT.)
 Inheritance hierarchy
 Inheritance relationships: tree-like hierarchy structure
 Each class becomes
 superclass
 Supply members to other classes

OR
 subclass

 Inherit members from other classes

6 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
FIG. 9.2 | INHERITANCE HIERARCHY FOR UNIVERSITY
COMMUNITYMEMBERS

7 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
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.
+getColor(): String Returns the color.
+setColor(color: String): void Sets a new color. GeometricObject1
+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

Run
+getDiameter(): double +setHeight(height: double): void
+printCircle(): void +getArea(): double 8
+getPerimeter(): double

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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 properties 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
9
automatically invoked.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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
}
10

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
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

11

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
CAUTION

You must use the keyword super to call the


superclass constructor. Invoking a
superclass constructor’s name in a subclass
causes a syntax error. Java requires that the
statement that uses the keyword super
appear first in the constructor.

12

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
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) {
new Faculty();
}

public Faculty() {
System.out.println((4)"Faculty's no-arg constructor is invoked");
}

class Employee extends Person {
public Employee() {
this(“(2)Who I am?”)
System.out.println(“(3)Employee's no-arg constructor is
invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() { 13
System.out.println(“(1)Person's no-arg constructor is invoked");
} Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
DECLARING A SUBCLASS
A subclass extends properties and methods from the
superclass. You can also:
 Add new properties
 Add new methods
 Override the methods of the superclass

15

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
CALLING SUPERCLASS METHODS
You could rewrite the printCircle() method in the Circle class as
follows:

public void printCircle() {


System.out.println("The circle is created " +
super.getDateCreated() + " and the radius is " + radius);
}

16

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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;
}
}

17

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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.
18

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
NOTE

Like an instance method, a static method


can be inherited. However, a static method
cannot be overridden. If a static method
defined in the superclass is redefined in a
subclass, the method defined in the
superclass is hidden.

19

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
OVERRIDING VS. OVERLOADING

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

class A extends B { class A extends B {


// This method overrides the method in B // This method overloads the method in B
public void p(double i) { public void p(int i) {
System.out.println(i); System.out.println(i);
} }
} }

20

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
PROTECTED MEMBERS
 protected access
 Intermediate level of protection between public and
private
 protected members accessible by
 superclass members
 subclass members

 Subclass access to superclass member


 Keyword super and a dot (.)

21 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
COMMISSIONEMPLOYEE-BASEPLUSCOMMISSIONEMPLOYEE INHERITANCE HIERARCHY
USING PROTECTED INSTANCE VARIABLES

 Use protected instance variables


 Enable class BasePlusCommissionEmployee to
directly access superclass instance variables
 Superclass’s protected members are inherited by all
subclases of that superclass

22 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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
...
} }

23

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
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.

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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
CONSTRUCTOR
CALLS…
 There are some restrictions on how you can use the base
class constructor call super .
 Also, the call to the base class constructor ( super ) must
always be the first action taken in a constructor definition.
You cannot use it later in the definition of a constructor.
 Notice that you use the keyword super to call the
constructor of the base class. You do not use the name of the
constructor; you do not use
 Employee(theName, theDate); //ILLEGAL

25 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
CONSTRUCTOR
CALLS…
 If a constructor definition for a derived class does not
include an invocation of a constructor for the base class,
then the no-argument constructor of the base class is
invoked automatically as the first action of the derived
class constructor.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
 Within the definition of a constructor for a class, you can
use super as a name for a constructor of the base class.
Any invocation of super must be the first action taken by
the constructor.
 EXAMPLE
 public SalariedEmployee(SalariedEmployee originalObject)
{
 super(originalObject);
 salary = originalObject.salary;

}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
NOTES
 The inherited fields can be used directly, just like any other fields.
 You can declare a field in the subclass with the same name as the one
in the superclass, thus hiding it (not recommended).
 You can declare new fields in the subclass that are not in the
superclass.
 The inherited methods can be used directly as they are.
 You can write a new instance method in the subclass that has the
same signature as the one in the superclass, thus overriding it.
 You can declare new methods in the subclass that are not in the
superclass.
 You can write a subclass constructor that invokes the constructor of
the superclass, either implicitly or by using the keyword super.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
NOTES
 A subclass does not inherit the private members of its
parent class. However, if the superclass has public or
protected methods for accessing its private fields, these
can also be used by the subclass.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
AN OBJECT OF A DERIVED CLASS HAS
MORE THAN ONE TYPE
 An object of a derived class has the type of the derived
class, and it also has the type of the base class.
 More generally, a derived class has the type of every one
of its ancestor classes.
 So, you can assign an object of a derived class to a
variable of any ancestor type (but not the other way
around).
 You can plug in a derived class object for a parameter of
any of its ancestor types.
 More generally, you can use a derived class object
anyplace you can use an object of any of its ancestor
types.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
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

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

31

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
ACCESSIBILITY SUMMARY

32

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
VISIBILITY MODIFIERS

33

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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.
34

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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.

35

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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.

36

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807

You might also like