Csc435 Chapter 5 Part 2
Csc435 Chapter 5 Part 2
PROGRAMMING
TOPIC 5 PART 2
Inheritance
By Zulaile Mabni
Amended by Mohammad Bakri & Hajar Izzati Mohd Ghazalli
Inheritance concept
Inheriting instance fields and methods
Calling super class constructor and methods
OBJECTIVES Object class
Access levels – public, protected, private, package
Array of sub classes
Application of super and sub classes
THE OBJECT CLASS
A class called Object is defined in the java.lang package of the Java
standard class library.
All classes are derived from the Object class.
Thus the println method can call toString for any object that is passed
to it.
Inheritance concept
Inheriting instance fields and methods
Calling super class constructor and methods
6
MEMBER ACCESSIBILITY (CONT’D)
The methods of a sub classes objects can access both the public and
protected members of super class.
The methods of a sub classes objects cannot access the private members of
super class.
7
ACCESS MODIFIER
8
ACCESS MODIFIER
Same class
Inheritance concept
Inheriting instance fields and methods
Calling super class constructor and methods
Note in this example that once the array of Animals has been structured, it can
be used to store objects of any subclass of Animal.
ARRAY OF SUBCLASSES
Superclass: Animal
ARRAY OF SUBCLASSES
Subclass: Cow
ARRAY OF SUBCLASSES
Subclass: Dog
ARRAY OF SUBCLASSES
Subclass: Cat
Application: Animal Application
CHECKING OBJECT TYPE
To check which class an object is created from, we can use instanceof operator.
18
FOR EXAMPLE
We have:
CONT
Animal a[] = new Animal[10];
a[0] = new Frog(“fire-bellied”, “toad”);
a[1] = new Bird(“pigeon”, “white”);
As you can see, even though a[0]
contains object of Frog, we can’t call
a[0].sleep(); //valid the function jump() because the object
is currently stored in Animal data type.
a[1].sleep(); //valid Same with a[1]. Sleep() is valid
a[0].jump(); // not valid because it is declared in Animal, so it
is guaranteed that all classes that
a[1].fly(); // not valid inherit from it will contain the method.
20
CONT
To call the specific method in subclass when the subclass object is stored in superclass
data type, we need to cast the object into subclass data type.
21
TOSTRING
For subclasses’ toString() method, we can just call the superclass toString()
method and concat with the new variable inside the subclass. For example,
toString() function for class Frog: