Sie sind auf Seite 1von 40

Chapter 4

Inheritance
,Abstract Class
and interface

Prepared by :
Puan Robiah
Hamzah

Objectives

Describe encapsulation, polymorphism,


and inheritance terminology
Develop a subclass from a superclass
through inheritance
Overriding method in the subclass
Abstract class and interface.
Summary

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)

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

Visibility Modifiers
package p1;
public class C1 {
public int x;
protected int y;
int z;
private int u;

protected void m() {


}

public class C2 {
C1 o = new C1();
can access o.x;
can access o.y;
can access o.z;
cannot access o.u;
}

can invoke o.m();

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;

can invoke m();


}

public class C5 {
C1 o = new C1();
can access o.x;
cannot access o.y;
cannot access o.z;
cannot access o.u;

can invoke m();


}

cannot invoke o.m();

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

Are superclasss Constructor


Inherited?
No. They are not inherited.
They are invoked explicitly or implicitly.
Explicitly using the super keyword.

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

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
}

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.

Overriding vs. Overloading


public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
}
}

public class Test {


public static void main(String[] args) {
A a = new A();
a.p(10);
}
}

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.

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.
public String toString() {
return color: +color + and is filled:
+filled;
}
You can also s.o.p(loan.toString() with s.o.p(loan)

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

Abstract Superclasses and Abstract


Methods
When we define a superclass, we
often do not need to create any
instances of the superclass.

Definition: Abstract Class


An abstract class is a class
defined with the modifier abstract OR
that contains an abstract method OR
that does not provide an implementation of an inherited
abstract method
An abstract method is a method with the keyword abstract,
and it ends with a semicolon instead of a method body.
Private methods and static methods may not be declared
abstract.
No instances can be created from an abstract class.

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.

Which Approach to Use ?


The best approach depends on the
particular situation.
When considering design options, we
can ask ourselves which approach
allows easier modification and
extension.

Solution to case 1 and 2 ?


Could all of you draw the UML diagrams
to show the class inheritance for case 1
and 2 ?
In UML, the abstract class and method
is written in italic.
Just draw to reflect your understanding
on abstract class and method Its ok
to make mistake now but the later
one will not be forgiven..
May be the next slide helps you to
produce the correct UML diagram

Other example : The abstract


Vehicle
abstract
Vehicle

+ Vehicle(int year , double


price)
+ DisplayVehicleDetails ( )

class
abstract
method
( no
implementat
ion )

extends
(isa)
Car
+ Car(double cc)
+ DisplayVehicleDetails
()

Aeroplane

+ Aeroplane(int bilPassenger)
+ DisplayVehicleDetails ( )

concrete method
( with
implementation )

Lets program.. : Polymorphism and


Abstract
class
Create an abstract class named Vehicle. Data member is
manufacturedYear and price per unit. Method member is an
abstract method named DisplayVehicleDetails().
Derive two classes from the Vehicle class: Car which also contains
a field for cc value and Aeroplane which contains a variable to
hold the number of passengers allowable. Each of the subclass has
the implementation of the polymorphic DisplayVehicleDetails()
which will display the details of Car and Aeroplane objects.
Write a simple program to allow the client code (eg: Test class) to
create Car object and Aeroplane object. Assign them to variables of
class Vehicle. Use these objects to call DisplayVehicleDetails() to
display the detail of both Car an Aeroplane objects.

Filenames :
Test.java (client code)
Vehicle.java

public class Test


{
public static void main(String[] args)
{
Vehicle ride1 = new Car(1.5);
Vehicle ride2 = new Aeroplane(1000);

ride1.DisplayVehicleDetails();
ride2.DisplayVehicleDetails();

public abstract class Vehicle


{
protected int manufacturedYear;
protected double price;

//

call polymorphic method

// Vehicle constructor

public abstract void DisplayVehicleDetails( );


}

// use polymorphism

// Vehicle class is abstract class

protected Vehicle(int year,double price)


{
manufacturedYear = year;
this.price = price;
}

Solution

// abstract method

Filename :
Car.java

Solution(cont)

public class Car extends Vehicle


{
protected double cc;
public Car(double cc)
{
super(2006 , 100000.0);
this.cc = cc;
}

// Car constructor

public void DisplayVehicleDetails( ) // display Car details


{
System.out.println( Car details :\n);
System.out.println( Year Manufactured : +
manufacturedYear);
System.out.println( Price : + price);
System.out.println( CC : + cc);
}

Filename :
Aeroplane.java

public class Aeroplane extends Vehicle


{
protected int billPassenger;

public Aeroplane(int passenger)


{
super(1990 , 500000.0);
billPassenger = passenger;
}
details

public void DisplayVehicleDetail()

// Aeroplane constructor

// display Aeroplane

billPassenger);
}
}

System.out.println( Aeroplane details :\n);


System.out.println( Year Manufactured : +
manufacturedYear);
System.out.println( Price : + price);
System.out.println( Bill passenger : +

Inheritance versus Interface


The Java interface is used to share
common behavior (only method headers)
among the instances of different classes.
Inheritance is used to share common code
(including both data members and methods)
among the instances of related classes.
In your program designs, remember to use
the Java interface to share common
behavior. Use inheritance to share common
code.
If an entity A is a specialized form of another
entity B, then model them by using
inheritance. Declare A as a subclass of B.

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 :

public class Aeroplane implements Flyer


{
}

The Flyer example


public interface Flyer
{
public void takeOff ( );
public void land ( );
public void fly ( );
}
public class
{
public
{
}
public
{
}
public
{
}
}

<<interface
>>
Flyer
+ takeOff ( )
+ land ( )
+ fly ( )

Aeroplane implements Flyer


void takeOff ( )

implements
(is-a-kindof)

void land( )
void fly( )

Aeroplane
+ takeOff ( )
+ land ( )
+ fly ( )

The Flyer interface and Aeroplane


Implementation

The Flyer example


<<interface
>>
Flyer

implement

+ takeOff
+ land ( )
+ fly ( )

Aeroplane

+ takeOff ( )
+ land ( )
+ fly ( )

(is-a-kindof)

Bird
+
+
+
+
+

takeOff ( )
land ( )
fly ( )
buildNest ( )
layEggs ( )

Superman
+
+
+
+
+

takeOff ( )
land ( )
fly ( )
leapBuilding ( )
stopBullet ( )

Multiple implementations of the Flyer


Interface

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

A mixture of Inheritance and


Implementation

Superman
+
+
+
+
+

takeOff ( )
land ( )
fly ( )
leapBuilding ( )
stopBullet ( )

Summary

Inheritance is-a relationship


Abstract class must apply method overriding
Abstract modifier able to cover for class and method
Interface- share the common behavior only (method
body)
Inheritance able to share both common data member
and methods
Polymorphism allows a single variable to refer to
objects from different subclasses in the same
inheritance hierarchy
Interface using the is a kind of relationship
Abstract method MUST apply method overriding
because abstract method only have method header
at abstract class. The details is at concrete class.
Inheritance able to use method overriding

Das könnte Ihnen auch gefallen