0% found this document useful (0 votes)
29 views28 pages

7 Inheritance

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

7 Inheritance

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

Chapter 11

Inheritance and
Polymorphism

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Can you notice
any issues?

public class Circle { public class Rectangle {


String color; String color;
boolean filled; boolean filled;
double radius; double width, height;
Circle () { Rectangle () {

} }
f1() { …. } f1() { …. }
f2() { …. } f2() { …. }
f3() { f4() {

} }
} }
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
public class GeometricObject {
String color;
boolean filled;
GeometricObject(){ Creating a new
} class with
f1() { …. } common code
f2() { …. }
}

public class Circle { public class Rectangle {


String color; String color;
boolean filled; boolean filled;
double radius; double width, height;
Circle () { Rectangle () {

} }
f1() { …. } f1() { …. }
f2() { …. } f2() { …. }
f3() { f4() {

} }
} }
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
public class GeometricObject {
String color;
boolean filled;
GeometricObject(){ Making the
} connection
f1() { …. }
f2() { …. }
}

public class Circle extends GeometricObject { public class Rectangle extends GeometricObject {

double radius; double width, height;


Circle () { Rectangle () {

} }

f3() { f4() {

} }
} }
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
The
public class GeometricObject { hierarchy
String color;
boolean filled; Parent Class
GeometricObject(){ GeometricObject
Base Class
} Super Class
f1() { …. }
isA Relation
f2() { …. }
} Circle Rectangle

public class Circle extends GeometricObject { public class Rectangle extends GeometricObject {

double radius; double width, height;


Circle () { Rectangle () {
Child class
} Extended Class }
Derived Class
Sub Class
f3() { f4() {
super.color = 5; super.color = 5;
super.f1(); super.f1();
} }
} }
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
public class GeometricObject {
String color;
boolean filled; Parent Class • A child class can have a single
GeometricObject(){ Base Class parent class
} Super Class • Single vs Multiple inheritance
f1() { …. } • Child cannot access private
f2() { …. } data field/method of its parent
}

public class Circle extends GeometricObject { public class Rectangle extends GeometricObject {

double radius; double width, height;


Circle () { Rectangle () {
Child class
} Extended Class }
Derived Class
Sub Class
f3() { f4() {
super.color = 5; super.color = 5;
super.f1(); super.f1();
} }
} }
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
In a driver class:
public class GeometricObject {
Circle c0 = new Circle ();
String color;
boolean filled; Parent Class color =?
GeometricObject(){ Base Class filled = ?
…… } Super Class
f1() { …. }
f2() { …. }
} radius =?

public class Circle extends GeometricObject { public class Rectangle extends GeometricObject {

double radius; double width, height;


Circle () { Rectangle () {
super(); Child class super();
…… } Extended Class …… }
Derived Class
Sub Class
f3() { f4() {
super.color = 5; super.color = 5;
super.f1(); super.f1();
} }
} }
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.

Object oriented programming allows you to derive new classes


from existing classes. This is called inheritance.

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
-radius: double -width: double
+Circle() -height: double Rectangle1
+Circle(radius: double) +Rectangle()
+Circle(radius: double, color: String, +Rectangle(width: double, height: double)
filled: boolean) +Rectangle(width: double, height: double
color: String, filled: boolean)
+getRadius(): double
+setRadius(radius: double): void +getWidth(): double
TestCircleRectangle
+getArea(): double +setWidth(width: double): void
+getPerimeter(): double +getHeight(): double
+getDiameter(): double +setHeight(height: double): void
+printCircle(): void +getArea(): double
+getPerimeter(): double

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

• A subclass is not a subset of its superclass. Subclass


usually contains more information and methods
than its superclass
• Private data fields in a superclass are not accessible
outside the class. You may need to use
accessor/mutator
• Java doesn’t allow to derive a subclass from several
classes. No multiple inheritance. So only one
parent class for a subclass

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

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

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.
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) 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
} rights reserved. 0132130807
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Example on the Impact of a Superclass without
no-arg Constructor

Find out the errors in the program:


public class Apple extends Fruit {
}

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

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

It is not necessary to put super before getDateCreated()

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

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.

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.

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

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

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.

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

• A type defined by subclass is subtype and a type


defined by superclass is supertype.

• You can pass an instance of a subclass to a


parameter of its superclass type

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

A D

B C E F

Declared class Actual class


C c = new C(); // C is the most specific class of c and O is the most general class of c
A c = new C(); c.datafield
O c = new C(); c.method()

D c = new C();

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

+ name: String
+ credit: int
Student (name: String, credit: int)
+toString(): String

RegularStudent ScholarshipStudent

- scholarshipPercent : int

RegularStudent (name: String, credit: int) ScholarshipStudent (name: String,


+ calculateTuition(): double credit: int, scholarshipPercent : int)
+toString(): String + calculateTuition(): double
+toString(): String

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy