You are on page 1of 46

www.espirity.

com

Inheritance
Dwight Deugo (dwight@espirity.com)
Nesa Matic (nesa@espirity.com)

Additional Contributors

None as of September, 2004

2003-2004, Espirity Inc.

Module Overview
1. Inheritance
2. Interfaces
3. Type Hierarchy in Eclipse

2003-2004, Espirity Inc.

Module Road Map


1. Inheritance

2.
3.

What is inheritance?
Class hierarchies
Method lookup in Java
Use of this and super
Constructors and inheritance
Abstract classes and methods
Interfaces
Type Hierarchy in Eclipse

2003-2004, Espirity Inc.

What is Inheritance?

Inheritance is one of the main objectoriented principals

Commonalities are stored in a parent class

It promotes reuse
It is a mechanism for sharing commonalities
between classes
Also called superclass

Commonalities are shared between


children classes

Also called subclasses


5

2003-2004, Espirity Inc.

Specialization and Generalization


client
premium
policyNumbe
r
getClient
setClient

HomePolicy

AutoPolicy

house

auto

getHouse
setHouse

getAuto
setAuto
6

LifePolicy

specialization

generalization

Policy

2003-2004, Espirity Inc.

Defining Inheritance

In Java, inheritance is supported by


using keyword extends

It is said that subclass extends superclass


If class definition does not specify explicit
superclass, its superclass is Object class
public
public
public
public

class
class
class
class

public class Policy{

Policy{
HomePolicy extends Policy{
AutoPolicy extends Policy{
LifePolicy extends Policy{
public class Policy extends Object{

2003-2004, Espirity Inc.

Variables and Inheritance

Variables can be declared as generic


types, and assigned objects of more
specific types

Variable declared as of type Policy can be


assigned an
instance
Policy
policy; of any Policys
subclassesPolicy = new Policy();
Policy policy;
Policy = new HomePolicy();
Policy policy;
Policy = new AutoPolicy();
Policy policy;
Policy = new LifePolicy();

2003-2004, Espirity Inc.

Multiple Inheritance

Not supported in Java

A class cannot extend more than one class


There is only one direct superclass for any
class

Object class is exception as it does not have


superclass

2003-2004, Espirity Inc.

What is Inherited?

In general all subclasses inherit from


superclass:

Data
Behavior

When we map these to Java it means


that subclasses inherit:

Fields (instance variables)


Methods

10

2003-2004, Espirity Inc.

Inheriting Fields

All fields from superclasses are


inherited by a subclass

Inheritance goes all the way up the


hierarchy
client
premium
policyNumber

house

Policy

HomePolicy

11

client
premium
policyNumber

client
premium
policyNumber
house

2003-2004, Espirity Inc.

Inheriting Methods

All methods from superclasses are


inherited by a subclass

Inheritance goes all the way up the


getClient
getClient
hierarchy
setClient
setClient
getPremium
Policy
setPremium
getPolicyNumber
setPolicyNumber
getHouse
setHouse

HomePolicy

12

getPremium
setPremium
getPolicyNumber
setPolicyNumber
getClient
setClient
getPremium
setPremium
getPolicyNumber
setPolicyNumber
getHouse
setHouse
2003-2004, Espirity Inc.

Method Lookup

Method lookup begins in the class of


that object that receives a message

HomePolicy homePolicy = new HomePolicy();

homePolicy.getPremium();

HomePolic
house
y

getHouse
HomePolicy class method not found setHouse

If method is not found lookup continues


Policy
in the superclass
Policy class method found

13

premium

getPremiu
m
setPremiu
m 2003-2004, Espirity Inc.

this vs. super

They are both names of the receiver


object
The difference is where the method
lookup begins:

this

Lookup begins in the receiver objects class

super

Lookup begins in the superclass of the class


where the method is defined

14

2003-2004, Espirity Inc.

Example
public void print(){
System.out.println("A " + getClass().getName() + ", $" + getPremium());
}

policy.print();

A Policy, $1,200.00

Console

Policy

HomePolicy
public void print(){
super.print();
System.out.println("for house " + getHouse().toString();
}

homePolicy.print();

A HomePolicy, $1,200.00
for house 200 Great Street

15

Console

2003-2004, Espirity Inc.

Method Overriding

If a class define same method as its


superclass, it is said that the method is
overridden
Policy

Method signatures must match


HomePolicy

//Method in the Policy class


public void print(){
System.out.println("A " + getClass().getName() + ", $" +
}

getPremium());

//Overridden method in the HomePolicy class


public String toString(){
super.print();
System.out.println("for house " + getHouse().toString();
}

16

2003-2004, Espirity Inc.

Overriding Constructors

Similar to overriding methods, applying


rules specific to constructors:

First line in the constructor must be either


this(parameters) or super(parameters)

This eventually leads to the Object class


constructor that creates the object
If the call is not coded explicitly then an implicit
zero-argument super() is called
If the superclass does not have a zeroargument constructor, this causes an error

17

2003-2004, Espirity Inc.

Example of Overriding Constructors


public Policy(double premium, Client aClient, String policyNumber){
this.premium = premium;
this.policyNumber = policyNumber;
this.client = aClient;
}

Policy

HomePolicy
public HomePolicy(double premium,Client aClient,String policyNumber,House aHouse)
{
super(premium, aClient, policyNumber);
this.house = aHouse;
}

18

2003-2004, Espirity Inc.

Abstracts Classes

Classes that cannot have instances

They also define what subclasses


should implement

They are designed to hold inherited fields


and methods for subclasses

Details are left for concrete


implementation in subclasses

Usually specified at the design level

19

2003-2004, Espirity Inc.

Defining Abstract Classes

Modifier abstract is used to indicate


abstract class
public abstract class Policy {

Policy

HomePolicy

AutoPolicy

20

LifePolicy

2003-2004, Espirity Inc.

Abstract Methods

Can only be defined in abstract classes

Declare method signatures

Abstract classes can contain concrete methods as


well
Declaration of abstract method in concrete class
will result in compile error
Implementation is left to the subclasess
Each subclass must have concrete
implementation of the abstract method

Used to impose method implementation on


subclasses
21

2003-2004, Espirity Inc.

Defining Abstract Methods

Modifier abstract is also used to


indicate abstract method
public abstract class Policy{
public abstract void calculateFullPremium();

Policy
calculateFullPremium

HomePolicy

AutoPolicy

22

LifePolicy

2003-2004, Espirity Inc.

Defining Abstract Methods

All subclasses must implement all


abstract methods

public class HomePolicy{


public void calculateFullPremium(){
//calculation may depend on a criteria about the house
}
public class AutoPolicy{
public void calculateFullPremium(){
//calculation may depend on a criteria about the auto
}
public class LifePolicy{
public void calculateFullPremium(){
//calculation may depend on a criteria about the client
}

23

2003-2004, Espirity Inc.

Module Road Map


1.

Inheritance

2. Interfaces

3.

What is an interface?
Defining interfaces
Using Interfaces
Type Hierarchy in Eclipse

24

2003-2004, Espirity Inc.

What is Interface?

Interfaces define a type and protocol but


do not provide implementation of that
protocol

Classes that implement interfaces must


provide implementation for defined protocol
Interfaces capture common behavior of the
classes that implement them

Commonly used to:

Impose protocol on set of classes that


implement interface
Indicate certain Java type (marker interfaces)
25

2003-2004, Espirity Inc.

Interfaces Define Types

Interfaces are, in a way, a higher


abstraction of Java types

They define common protocol


Are commonly used where types need to be
imposed but implementation is not important

For example in distributed programming

Interfaces are used to impose typing

If variable is declared as of interface type,


than instance of any class that implements
that interface can be assigned to that variable
26

2003-2004, Espirity Inc.

Defining Interface

Similar to defining classes

Keyword interface used instead of class


keyword
Defined methods contain signatures only
public interface Policyable{
public Policy createPolicy();
}
public interface Transferable{
}

Interfaces are also stored in .java files


27

2003-2004, Espirity Inc.

Rules

Interfaces can contain:

Only method signatures


Only final static fields

Interfaces cannot contain:

Any
Any
Any
Any

fields other than final static fields


static methods
method implementation
constructors

28

2003-2004, Espirity Inc.

Classes and Interfaces

At the design level interfaces are


usually indicated with a stereotype
<<interface>>
Instead of solid line, there is a dashed
line between
a
class
and
interfaces
it
Building
implements
<<interface>>
Policyable

House

29

2003-2004, Espirity Inc.

Implementing Interfaces

Classes implement interfaces

Keyword implements is used


They must define all methods that
interface they implement declares

public class House extends Building implements Policyable{


public Policy createPolicy(){
HomePolicy policy = new HomePolicy(this);
return policy;
}
}

30

2003-2004, Espirity Inc.

Interfaces are Inherited

It is possible that one interface extends


other interfaces

Known as sybtyping in Java


Multiple inheritance is allowed with
interfaces

Inheritance works the same as with


classes

All methods defined are inherited


There is a hierarchy of interfaces that exists
in parallel to class hierarchy
31

2003-2004, Espirity Inc.

Extending Interfaces
public interface Car {
public String getSpeed();
}

<<interface>
Car

public interface Color {


public String getBaseColor();
}

<<interface>
Color

<<interface>
ColoredCar
public interface ColoredCar extends Car, Color {
public String getSpeed();
public String getBaseColor();
}

32

2003-2004, Espirity Inc.

Naming Conventions

There are few conventions when naming


interfaces:

Suffix able is used for interfaces

Nouns are used for implementing classes names,


and I + noun for interfaces

Cloneable, Serializable, and Transferable

Interfaces: IColor, ICar, and IColoredCar


Classes: Color, Car, and ColoredCar

Nouns are used for interfaces names, and


noun+Impl for implementing classes

Interfaces: Color, Car, and ColoredCar


Classes: ColorImpl, CarImpl, and ColoredCarImpl
33

2003-2004, Espirity Inc.

Cross-Hierarchy Polymorphism

Allows classes across different


hierarchies to share common protocols

Supported and imposed by use of


interfaces

Building

House

Vehicle

<<interface>>
Policyable

34

Auto

2003-2004, Espirity Inc.

Implementation
public class PolicyFactory{
public Policy createPolicy(House aHouse){
return aHouse.createPolicy();
}
public Policy createPolicy(Auto anAuto){
return aHouse.createPolicy();
}

public class PolicyFactory{


public Policy createPolicy(Policyable aPolicyable){
return aPolicyable.createPolicy();
}
}

35

2003-2004, Espirity Inc.

Module Road Map


1.
2.

Inheritance
Interfaces

3. Type Hierarchy in Eclipse

Java types
Type casing
Eclipse type hierarchy
Supertype and subtype hierarchies

36

2003-2004, Espirity Inc.

Java Types

Variable can be declared as:

Reference type

Any instance of that class or any of the


subclasses can be assigned to the variable

Interface type

Any instance of any class that implements that


interface can be assigned to the variable
Policy policy;
policy = new AutoPolicy();
policy = new HomePolicy();
Policable policableObject;
policableObject = new Auto();
policableObject = new House();

37

2003-2004, Espirity Inc.

Variables and Messages

If variable is defined as a certain type,


only messages defined for that type
can be sent to the variable

This may cause a problem if variable is


assigned to an instance of a subtype that
defines different messages
Policy

AutoPolicy

Policy policy;
policy = new AutoPolicy();
policy.getAuto(); //ERROR

getAuto()
38

2003-2004, Espirity Inc.

Type Casting

Allows for sending messages not defined


by the declared superclass type by casting
variable to the actual subclass type
Policy policy;
policy = new AutoPolicy();
((AutoPolicy)policy).getAuto();

This type cast is temporary

The declared type of the variable stays the


same
Allows for messages to be sent to subtype
39

2003-2004, Espirity Inc.

Legal Type Casting?

Typecasting can be done on any


subtypes of the declared type
A
B

D
E

//lets say that message() is defined


//in class A
//declare variable of type A
A variable;
//assign instance of class E to the
//variable
variable = new E();
((B)variable).message(); //VALID
((A)variable).message(); //VALID
((D)variable).message(); //VALID
((E)variable).message(); //VALID
((C)variable).message(); //NOT VALID

40

2003-2004, Espirity Inc.

Eclipse and Inheritance

When creating class in Eclipse, wizards


can be used to setup class details
related to the inheritance

Abstract classes and super class specified

Eclipse has built-in support for viewing


and browsing different type hierarchies

These include supertype and subtype


hierarchies

41

2003-2004, Espirity Inc.

Eclipse Type Hierarchy

Opened by choosing Open Type Hierarchy


option from the context menu on the class
Hierarchy View that opens represents a
hierarchy of the chosen class

42

2003-2004, Espirity Inc.

Supertype Hierarchy

Opened by click on the Supertype Hierarchy


toolbar button of the Hierarchy view

Hierarchy View shows the class and its


superclasses

43

2003-2004, Espirity Inc.

Subtype Hierarchy

Opened by click on the Subtype Hierarchy


toolbar button of the Hierarchy view

Hierarchy View shows the class and its


subclasses

44

2003-2004, Espirity Inc.

Review

In this module we discussed:

Inheritance
Method lookup in Java
Use of this and super
Abstract classes and methods
Interfaces
Classes and interfaces
Polymorphism and inheritance
Type hierarchies in Eclipse
45

2003-2004, Espirity Inc.

Labs!

Lab: Inheritance

46

2003-2004, Espirity Inc.

You might also like