0% found this document useful (0 votes)
18 views52 pages

Chapter 6 - Part 1

The document discusses object-oriented programming concepts, focusing on inheritance and polymorphism, with examples of geometric shapes like Circle, Rectangle, and Triangle. It emphasizes the importance of reusing code through inheritance, the relationship between superclasses and subclasses, and the invocation of superclass constructors. Learning outcomes include developing subclasses, overriding methods, and understanding constructor chaining.

Uploaded by

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

Chapter 6 - Part 1

The document discusses object-oriented programming concepts, focusing on inheritance and polymorphism, with examples of geometric shapes like Circle, Rectangle, and Triangle. It emphasizes the importance of reusing code through inheritance, the relationship between superclasses and subclasses, and the invocation of superclass constructors. Learning outcomes include developing subclasses, overriding methods, and understanding constructor chaining.

Uploaded by

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

BACS2023

Object-Oriented Programming

Inheritance & Polymorphism

Chapter 6 – Part 1
A scenario (1)
Suppose you have created the following 3 classes for an application:
Circle Rectangle Triangle
-color: String -color: String -color: String
-radius: double -length: double -base: double
-width: double -height: double
+getColor(): String +getColor(): String +getColor(): String
+setColor(color:String): void +setColor(color:String): void +setColor(color:String): void
+getRadius(): double +getLength(): double +getBase(): double
+setRadius(radius: double): void +setLength(length: double): void +setBase(base: double): void
+getArea(): double +getWidth(): double +getHeight(): double
+setWidth(width: double): void +setHeight(height: double): void
+getArea(): double +getArea(): double

▪ If the client now wants to record the date created of each Circle, Rectangle and
Triangle object, what would you do?
▪ A few weeks later, the client informs you that he also wants the fill status of each
Circle, Rectangle and Triangle object to be recorded …
What would you do ?
A scenario (2)
Circle Rectangle Triangle
-color: String -color: String -color: String
-radius: double -length: double -base: double
-width: double -height: double
+getColor(): String +getColor(): String +getColor(): String
+setColor(color:String): void +setColor(color:String): void +setColor(color:String): void
+getRadius(): double +getLength(): double +getBase(): double
+setRadius(radius: double): void +setLength(length: double): void +setBase(base: double): void
+getArea(): double +getWidth(): double +getHeight(): double
+setWidth(width: double): void +setHeight(height: double): void
+getArea(): double +getArea(): double

■ Notice the common properties and behaviors in the 3 classes.


■ What is the best way to design these classes to avoid redundancy?
■ Could these common properties and behaviors be extracted and placed in a more
general class?
■ If so, you would only need to make changes to this general class.
Learning Outcomes
At the end of this chapter, you should be able to
■Develop a subclass from a superclass through inheritance.
■Invoke the superclass’s constructors using the super keyword.
■Describe constructor chaining.
■Override methods in the subclass.
■Override the useful methods toString() and equals(Object)
from the Object class. Distinguish differences between overriding
and overloading.
1. Introduction to Inheritance (1)
■Inheritance is an important and powerful feature for
reusing software.
■In fact, every class you define in Java is inherited from an
existing class, either explicitly or implicitly.
■The classes that you created so far were all extended
implicitly from the java.lang.Object class.
Introduction to Inheritance (2)
■Inheritance is one of the three
foundation principles of OOP Bank account
because it allows the creation of
hierarchical classifications.
■Using inheritance, you can create Saving account Checking account
a general class that defines traits
common to a set of related items.
■This class can then be inherited
Senior Children
by other, more specific classes, citizen account
each adding properties and account

behaviors that are unique to


them.
2. Superclasses and Subclasses (1)
C1 Superclass
Bank account

Inherits

C2 Saving Checking
account account Subclass

• If a class C2 is derived or inherited from another class called C1, then C2 is


called a subclass, and C1 is called a superclass.
Superclasses and Subclasses (2)
■A subclass
■inherits all the data members Bank account
and methods of its superclass.
■Defines its own (additional)
new data and methods, i.e. they
usually have more functionality Saving Checking
than their superclasses. account account

Term Aliases
Subclass Child Class, Extended Class or Derived Class
Superclass Parent Class, Base Class
Refer to the following classes
under folder Demo 6.1:
▪ GeometricObject
▪ Circle
▪ Rectangle
▪ TestCircleRectangle
Superclasses and Subclasses (3)
■Java supports inheritance by using the extends keyword.
■Thus, the subclass adds to (extends) the superclass. This is an
important and powerful concept in object-oriented
programming.
■Example:

class Circle extends GeometricObject{


. . .
}
import java.util.Date;
public class GeometricObj {
private String color = "white"; public class Rectangle extends GeometricObj {
private double width;
private Date dateCreated; private double height;
public GeometricObj() ……..
{ dateCreated = new Date(); } public double getArea()
public String getColor() { return width * height; }
}
{ return color; }
public void setColor(String color)
{ this.color = color; }
…..
}
public class TestCircleRectangle {
public static void main(String[] args) {
public class Circle extends GeometricObj { Circle c = new Circle(1);
private double radius; System.out.println(“Area = "+ c.getArea());
public Circle() { } System.out.println(“Colour is “+ c.getColor());
public Circle(double radius) Rectangle r = new Rectangle(2,4);
{ this.radius = radius; } System.out.println(“Area = "+ r.getArea());
……. r.setColor("blue");
public double getArea() System.out.println(“Colour is " + r.getColor());
{ return radius * radius * Math.PI; } }
……. }
} 9-11
Superclasses and Subclasses (4)
■ The Circle and Rectangle
class will inherit from the
GeometricObject the data fields
■ color
■ filled
■ dateCreated

and the methods


■ getColor()
■ setColor()
■ isFilled()
■ setFilled()
■ getDateCreated()
Superclasses and Subclasses (5)
■Note, however, that private data fields and methods in a
superclass are not accessible in its subclasses.
■To refer to the data fields color, dateCreated , and filled , use
the get and set methods .
■The inherited public methods may be invoked by any of
the subclasses’ instances.
■Thus, as GeometricObject’s getColor(), setColor(),
getDateCreated(), isFilled() and setFilled() methods
are declared as public, these methods may be invoked by any
Circle or Rectangle objects.
3. Rationale for using inheritance (1)
■ Reuse
■Inheritance allows you to reuse the code from a previous programming
project without starting from scratch to reinvent the code.
■E.g., if we want to have a class called Cylinder to store the radius and
length of a cylinder, we can derive the Cylinder class from the
Circle class.
■Although the new class might be slightly different from the old,
inheritance allows you to build on what was done previously.
GeometricObject

Circle Rectangle

Cylinder
Rationale for using inheritance (2)
■ Class hierarchy
■Inheritance allows you to build a hierarchy among classes.
■Example:-
■A general GeometricObject class is used to define general variables
of a geometric object (e.g. object color) and methods (e.g.
setColor()) that are common to all geometric objects.
■The Circle class and Rectangle class which represents specific
geometric objects can both be derived from the GeometricObject
class
GeometricObject

Circle Rectangle
Note
■A subclass is not a subset of its
superclass. GeometricObject
■Rather, a subclass is an extension of its
superclass as it contains more information
and functions than its superclass.
Circle Rectangle
■Inheritance is used to model the is-a
relationship.
■Hence, a subclass and its superclass must
have the is-a relationship.
■In Java, multiple inheritance is not
Superclass1 Superclass 2
allowed - only single inheritance is
allowed.
subclass
4. Superclass Constructors
▪Superclass’ constructors are not inherited by its subclasses.
▪The superclasses and subclasses have their own constructors
(whether default or explicit).
▪ The constructor for the superclass constructs the superclass
portion of the object whereas the constructors for the subclass
constructs the subclass part.
Invoking superclass’s constructor
▪ A superclass’s constructors will be invoked in its subclasses’ constructors
▪ They are invoked explicitly or implicitly.
▪ Explicitly using the super keyword.
▪ If the keyword super is not explicitly used, the superclass's no-arg constructor
is automatically invoked.
public class Circle extends GeometricObject {
import java.util.Date; private double radius;
public class GeometricObject {
private String color; public Circle(String c, double r){
private Date dateCreated; super(c);
public GeometricObject(){ radius = r;
this(“Blue”); }
} public Circle(){
public GeometricObject(String c) { radius = 1.0;
color = c; }
dateCreated = new Date();
}
….
}
Superclass’s Constructor Is Always Invoked
▪ If none of the constructor is invoked explicitly, the compiler puts
super() as the first statement in the constructor.
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
Calling a Superclass’ Constructor
■Syntax to call a superclass constructor:
super(arguments);
■The statement super(arguments)must always be the first
statement executed inside a subclass constructor.

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.
5. Constructor Chaining
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
} Person
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}

class Employee extends Person {


Employee
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
Faculty
System.out.println(s);
} Constructing an instance of a class
}
invokes all the superclasses’ constructors
class Person {
public Person() {
along the inheritance chain. This is called
System.out.println("(1) Person's no-arg constructor is constructor chaining.
invoked");
}
}
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");
}
}
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");
}
}
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");
}
}
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 {


4. Invoke Employee(String)
public Employee() { constructor
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");
}
}
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);
}
}

class Person {
5. Invoke Person() constructor
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
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");
}
}
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);
}
}

class Person {
public Person() {
7. Execute println
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
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);
}
}

class Person {
public Person() {
8. Execute println
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
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 { 9. Execute println


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");
}
}
Constructor Chaining Example
■Refer to the following classes under folder Demo 6.2:
■GeometricObject
■Circle
■Rectangle
■TestCircleRectangle
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");
}
}

Design Guide:
▪It is better to provide a no-arg constructor for every class to ensure the
class is easy to extend and to avoid errors.
6. Overriding Methods in the Superclass (1)
▪ A subclass inherits methods from a superclass. A
subclass extends properties and methods from
the 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.
Overriding Methods in the Superclass (2)
public class GeometricObject {
// Other methods are omitted
public void display() {
System.out.println("\nColor: " + color + "\nFilled: " +
filled + "\nDate created: " + dateCreated);
}
}

public class Circle extends GeometricObject {


// Other methods are omitted
/** Override the display method defined in GeometricObject */
public void display() {
System.out.println("\nColor: " + getColor() + "\nFilled: " +
isFilled() + "\nDate created: " + getDateCreated() +
"\nRadius: " + radius);
}
}
Calling a Superclass’ Method (1)
■To invoke a superclass method from its subclass, use the
keyword super as follows:
super.method(arguments);
■super acts somewhat like this, except that it always
refers to the superclass of the subclass in which it is
used.
public class GeometricObject {
// Other methods are omitted
public void display() {
System.out.println("\nColor: " + color + "\nFilled: " +
filled + "\nDate created: " + dateCreated);
}
}

public class Circle extends GeometricObject {


………………
public void display() {
System.out.println("\nColor: " + getColor() + "\nFilled: " +
isFilled() + "\nDate created: " + getDateCreated() +
"\nRadius: " + radius);
}
}

public class Circle extends GeometricObject {


……………………
public void display() {
super.display();
System.out.println(“Radius: " + radius);
}
}
Calling a Superclass’ Method (2)
■Refer to the following classes in the Demo 6.3 folder to
see how the superclass’s display() method is
invoked in its subclasses:
■GeometricObject
■Circle
■Rectangle
■TestCircleRectangle
Calling a Superclass’ Method
public class DemoSuper{
public static void main(String [] args){
■You can use super.p() to invoke the
A x=new A();
method p() defined in the superclass. x.p();
Suppose A extends B and B extends C, }
}
and a method p() is defined in C. class A extends B{
■Can you invoke super.super.p() public void p(){
…….
from A? }
}
class B extends C{
….
}
class C{
public void p(){
System.out.println("In class C");
}
}
7. 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.
7.1 The toString method (1)
■ The Object class has a method called toString() with the following
method header:
public String toString()
■ The toString() method returns a string representation of the object.
■ The default implementation returns a string consisting of the object’s class
name, the @ sign, and the object’s hashcode in hex. E.g., the code
Circle c = new Circle();
System.out.println(c.toString());
displays something like Circle@15037e5 . This message is not very helpful or
informative.
■ Usually you should override the toString method so that it returns a
meaningful string representation of the object.
Overriding the toString Method
public class GeometricObject {
// Other methods are omitted
/** Override the toString method defined in Object */
public String toString() {
return “Color is ” + color + "\nFilled is " + filled +
“\Date created is ” + dateCreated;
}
}
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;
}
}
The toString method (2)
■Using an object reference as the argument in the println()
method will automatically invoke the object’s toString()
method.
■Thus,
System.out.println(circle)

is equivalent to invoking

System.out.println(circle.toString())
The toString method (3)
■Refer to the following classes in the Demo 6.4 folder to
see how the toString() method is overridden:
■GeometricObject
■Circle
■Rectangle
■TestCircleRectangle
7.2 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) {
if (o instanceof Circle) {
For example, the equals
return radius == ((Circle)o).radius;
method is overridden in the }
Circle class. else
return false;
}
NOTE
▪ The == comparison operator is used for
▪ comparing two primitive data type values or
▪ 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 method is modified in the defining
class of the objects.
▪ The == operator is stronger than the equals method, in that the ==
operator checks whether the two reference variables refer to the
same object.
8. Method Overriding (1)
■In a class hierarchy, when a method in a subclass has the same
return type and signature as a method in its superclass, the
methods in the subclass is said to override the method in the
superclass.
■When an overridden method is called from within a subclass, it
will always refer to the version of that method defined by the
subclass.

GeometricObject

public String toString()

Circle Rectangle
Method Overriding (2)
▪ 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.
public class GeometricObject {
private void display() {
System.out.println("\nColor: " + color + "\nFilled: " +
filled + "\nDate created: " + dateCreated);
}
}
public class Circle extends GeometricObject {
……………………
public void display() {
super.display(); //error
System.out.println(“Radius: " + radius);
}
}
Method Overriding (3)

▪ Like an instance method, a static method can be inherited.


▪If a static method defined in the superclass is redefined in a
subclass, the method defined in the superclass is hidden.
▪The hidden static methods can be invoked using the syntax
SuperClassName.staticMethodName.
public class GeometricObject {
…..
private static int numObjects=0;
public static int getNumObjects(){
return numObjects++;
}
public static void displayObj(){
System.out.println(“Objects:”+ numObjects);
}
} public class Circle extends GeometricObject {
…….
public String toString() {
return "\nObject = "+ getNumObjects() + super.toString ()+ "\nRadius: " + radius ;
}
public static void displayObj(){
GeometricObject.displayObj();
System.out.println(“Circles :”+getCircleObjCnt ());
}
} public class TestCircleRectangle {
public static void main(String[] args) {
Circle c = new Circle(1);
c.displayObj();
System.out.println("\n\nNumber of objects created "+ c.getNumObjects());
} 50
Method Overriding vs. Method Overloading

Method overriding occurs ONLY when the return types and signatures of the
two methods are identical. If they are not, then the two methods are simply
overloaded.
To Do
■Review the slides and source code for this chapter.
■Read up the relevant portions of the recommended text.
■Do the tutorial and complete the remaining practical
questions for this chapter.
■We shall selectively discuss them during class.

You might also like