Inheritance, Abstract Class and Interface: Prepared By: Puan Robiah Hamzah
Inheritance, Abstract Class and Interface: Prepared By: Puan Robiah Hamzah
Inheritance
,Abstract Class
and interface
Prepared by :
Puan Robiah
Hamzah
Objectives
Inheritance
is-a relationship
Single inheritance
Subclass is derived from one existing
class (superclass)
Multiple inheritance
Subclass is derived from more than
one superclass
Not supported by Java
In Java, a class can only extend the
definition of one class
Inheritance (continued)
General Syntax:
modifier(s) class ClassName extends ExistingClassName
modifier(s)
{
memberList
}
Inheritance Hierarchy
Inheritance Rules
1. The modifier protected makes a data member or method visible
and accessible to the instances of the class and the descendant
classes.
2. The private members of the superclass are private to the
superclass
3. The subclass can directly access the public members of the
superclass
4. The subclass can include additional data and/or method members
5.
The subclass can override, that is, redefine the public methods of the
superclass
However, this redefinition applies only to the objects of the subclass, not to the objects of the
superclass
6.
All data members of the superclass are also data members of the subclass
Similarly, the methods of the superclass (unless overridden) are also the methods of the
subclass
Remember Rule 1 when accessing a member of the superclass in the subclass
Inheritance (continued)
To write a methods definition of a
subclass, specify a call to the public
method of the superclass
If subclass overrides public method of
superclass, specify call to public method
of superclass:
super.MethodName(parameter list)
If subclass does not override public
method of superclass, specify call to
public method of superclass:
MethodName(parameter list)
Visibility Modifiers
package p1;
public class C1 {
public int x;
protected int y;
int z;
private int u;
public class C2 {
C1 o = new C1();
can access o.x;
can access o.y;
can access o.z;
cannot access o.u;
}
package p2;
public class C3
extends C1 {
can access x;
can access y;
can access z;
cannot access u;
}
public class C4
extends C1 {
can access x;
can access y;
cannot access z;
cannot access u;
public class C5 {
C1 o = new C1();
can access o.x;
cannot access o.y;
cannot access o.z;
cannot access o.u;
Accessibility Summary
Modifier
on members
in a class
Accessed
from the
same class
Accessed
from the
same package
Accessed
from a
subclass
Accessed
from a different
package
public
protected
default
private
Inheritance-example
Building
# size : String
# price :double
superclass
+ Building(size:String,
price:double)
House is a Building..
extends
(isa)
House
- houseNo : int
+ House (no:int)
+ displayHouseDetails( )
Inheritance hierarchy
subclass
Inheritance
Building
# size:String
# price:double
+ Building( size:String,
price:double )
extends
(isa)
House
- houseNo:int
+ House (HouseNo:int)
+ displayHouseDetails( )
publicclassBuilding
{protectedStringsize;
protecteddoubleprice;
publicBuilding(Stringsize,
doubleprice)
{this.size=size;
this.price=price;
}
// super is used to call superclass constructor
publicclassHouseextends Building
{privateinthouseNo;
publicHouse(inthouseNo)
{super(100X90,100000);
this.houseNo=houseNo;
}
Inheritance
publicclassBuilding
{protectedStringsize;
protecteddoubleprice;
publicBuilding(Stringsize,
doubleprice)
{this.size=size;
this.price=price;
}
}
(2)
publicclassHouseextends
Building
{privateinthouseNo;
publicHouse(inthouseNo)
{super(100X90,100000);
this.houseNo=houseNo;
}
publicvoid
displayHouseDetails()
{System.out.println(
Houseno:+houseNo);
System.out.println(
Size:+size);
publicclassTest
System.out.println(
{publicstaticvoidmain(String[] Price:+price);}
args)
(1)
}
{HousemyHouse=newHouse(8);
MyHouse.displayHouseDetails();
(1) and (2) : Execution flow between
}
classes
}
class B {
public void p(int i) {
}
}
class B {
public void p(int i) {
}
}
class A extends B {
// This method overrides the method in B
public void p(int i) {
System.out.println(i);
}
}
class A extends B {
// This method overloads the method in B
public void p(double i) {
System.out.println(i);
}
}
(a)
(b)
When you run Test class in (a), a.p(10) invokes the p(int i),
display 10,
Test class in (b), nothing is printed.
Method overriding
Circle
# radius : double
+ Circle()
+ Cirle(radius:double)
superclass
+ getRadius() : double
+
setRadius(radius:double)
+ findArea():double
Cylinder
- length : double
+ Cylinder()
+ Cylinder (radius:double, length:double)
+ getLength() :double
Overriding findArea() in
superclass
+ setLength(length:double):void
+ findArea():double
subclass
Circle.java
Method overriding
publicclassCircle
{protecteddoubleradius;
publicCircle()
Overloaded
constructors
{radius=1.0;
}
publicCircle(doubleradius)
{this.radius=radius;
}
publicdoublegetRadius()
{returnradius;
}
publicdoublesetRadius(doubleradius)
{this.radius=radius;
}
publicdoublefindArea()
This method will be
{returnradius*radius*3.14159; //
overrided in
}
Cylinder class
}
Method overriding
Cylinder.java
publicclassCylinderextendsCircle
Note :
{privatedoublelength;
Overriden method must
have the same signature
and
publicCylinder()
return type as its
superclass
{super();
length=1.0;
}
publicCylinder(doubleradius,doublelength)
{super(radius);
this.length=length;
}
publicdoublegetLength()
{returnlength;
}
publicdoublesetLength(doublelength)
{this.length=length;
// Modified findArea()
}
publicdoublefindArea()
{return2*super.findArea()+2*getRadius()*Math.PI*length;
}
}
Formular
2 *
circle area
+
cylinder body area
Method overriding
Eg :Test.java
publicclassTest
{publicstaticvoidmain(String[]args)
{Circlecircle=newCircle();
circle.findArea();// calls findArea() in Circle
Cylindercylinder=newCylinder(3.0,5.0);
cylinder.findArea();// calls findArea() in Cylinder
:
:
}
}
Polymorphism
Polymorphism allows a single variable to
refer to objects from different subclasses in
the same inheritance hierarchy
For example, if Cat and Dog are subclasses of
Pet, then the following statements are valid:
Pet myPet;
myPet = new Dog();
. . .
myPet = new Cat();
Case 1
Student Must Be Undergraduate or Graduate
If a student must be either an undergraduate or a
graduate student, we only need instances of
UndergraduateStudent or GraduateStudent.
Therefore, we must define the Student class so that
no instances may be created of it. To ensure this,
Student class must be declared abstract.
Let the ComputeCourseGrade() to be the abstract
method of Student class
Case 2
Student Does Not Have to Be
Undergraduate or Graduate.
In this case, we may design the Student
class in one of two ways.
We can make the Student class instantiable, OR
We can leave the Student class abstract and
add a third subclass, OtherStudent, to handle a
student who does not fall into the
UndergraduateStudent or GraduateStudent
categories.
class
abstract
method
( no
implementat
ion )
extends
(isa)
Car
+ Car(double cc)
+ DisplayVehicleDetails
()
Aeroplane
+ Aeroplane(int bilPassenger)
+ DisplayVehicleDetails ( )
concrete method
( with
implementation )
Filenames :
Test.java (client code)
Vehicle.java
ride1.DisplayVehicleDetails();
ride2.DisplayVehicleDetails();
//
// Vehicle constructor
// use polymorphism
Solution
// abstract method
Filename :
Car.java
Solution(cont)
// Car constructor
Filename :
Aeroplane.java
// Aeroplane constructor
// display Aeroplane
billPassenger);
}
}
interface
A java interface is a formal declaration in which
all methods contains no implementation
Many unrelated classes can implement the same
interface
A class can implement many unrelated interfaces
Example of java class declaration using interface :
<<interface
>>
Flyer
+ takeOff ( )
+ land ( )
+ fly ( )
implements
(is-a-kindof)
void land( )
void fly( )
Aeroplane
+ takeOff ( )
+ land ( )
+ fly ( )
implement
+ takeOff
+ land ( )
+ fly ( )
Aeroplane
+ takeOff ( )
+ land ( )
+ fly ( )
(is-a-kindof)
Bird
+
+
+
+
+
takeOff ( )
land ( )
fly ( )
buildNest ( )
layEggs ( )
Superman
+
+
+
+
+
takeOff ( )
land ( )
fly ( )
leapBuilding ( )
stopBullet ( )
Use of interfaces
We can say Aeroplane is a Vehicle, and it
can fly. A Bird is an animal, and it can fly.
These examples show that a class can
inherit from one class but also implement
some interfaces.
This is a solution for multiple inheritance
which is NOT allowed in Java.
The next slide shows the complete
diagram on how interface simulate
multiple inheritance
Inheritance and
Implementation
Animal
<<interface
>>
Flyer
Vehicle
+ eat ( )
+ takeOff
+ land ( )
+ fly ( )
HomoSapie
n
Aeroplane
+ takeOff ( )
+ land ( )
+ fly ( )
Bird
+
+
+
+
+
takeOff ( )
land ( )
fly ( )
buildNest ( )
layEggs ( )
Superman
+
+
+
+
+
takeOff ( )
land ( )
fly ( )
leapBuilding ( )
stopBullet ( )
Summary