Sei sulla pagina 1di 10

More on Inheritance

Supplementary reading:
Java text (e.g. Budd Ch. 8, 11)

Java tutorial
tutor al (http //www.cs.auckland.ac.nz/JavaCache/tutor al)
http://www.cs.auckland.ac.nz/JavaCache/tutorial
Trail: “Learning the Java Language”
Lessons: “Class and inheritance”,
“Interfaces and packages”

Forms of inheritance

„ Inheritance can be used in many


y ways:
y
„ Subclassing for specialisation
„ A subclass adds to its inherited properties
„ Subclassing for specification
„ A subclass implements behaviour that is defined by its
superclass
„ Subclassing for construction
„ A subclass extends a superclass for convenience alone
„ Subclassing
S b l i f for li
limitation
it ti
„ A subclass removes behaviour inherited from its superclass
„ Subclassing for combination
„ A new subclass is formed by inheriting from many superclasses

More on Inheritance COMPSCI 230 Software Design & Construction 2

More on Inheritance
Subclassing for specialisation
withdraw( ) only decrements the
balance if it stays in credit
„ The subclass alwaysy BankAccount
satisfies the balance : int
specification of its deposit( amount : int ) : void
superclass; i.e. the withdraw( amount : int ) : boolean

subclass is a subtype
„ In many cases properties
GoldAccount
are only added by the
subclass; inherited f
overdraftLimit : int

methods may / may not


be overridden withdraw( ) is overridden such
that the balance may fall below
„ The substitution principle zero, but only as much as the
holds true overdraft limit

More on Inheritance COMPSCI 230 Software Design & Construction 3

Subclassing for specification


<< abstract >>
Abstract superclass BankAccount
„ This is primarily concept that implements
reuse d
deposit(
i ( ) and
d
balance : int

„ An abstract superclass defines withdraw( ) deposit( amount : int ) : void


defines methods that should and applyInterest( ) withdraw( amount : int ) : boolean
be implemented by applyInterest( ) : void

subclasses; often the Abstract superclass


subclass doesn’t override any that implements
inherited methods move( ) and defines
„ With subclassing for paint( ) << abstract >> << interface >>
specification, subclasses are Shape Shape
move(( ) : void
realisations of the move( ) : void paint( ) : void
superclass’s abstract paint( ) : void
specification
„ The substitution principle is
preserved RectangleShape RectangleShape

Implements paint( )
Implements paint( )
More on Inheritance COMPSCI 230 Software Design & Construction and move( ) 4

More on Inheritance
Subclassing for construction
Class java.util.Vector Vector
implements the List
add( index : int, obj : Object ) : void
interface
„ This is code reuse, …

simply to allow a new


subclass to be
implemented quickly Stack

push( obj : Object ) : void


pop( ) : Object

Is a stack a vector? class Stack extends Vector {


public void push( Object obj ) {
// Always add to the start
In any case, what’s wrong // of the vector.
add( 0, obj );
with class Stack? }

}

More on Inheritance COMPSCI 230 Software Design & Construction 5

Subclassing for
construction class Vector {
private:
// Some sort of linear data structure.

„ In Java, a subclass can’t public:
void add( int index
index, Object*
Object obj ) {
drop methods inherited // Add obj at specified index.
}
from its superclass }

„ In C++, it is possible to class Stack : private Vector {


public:
create a subclass such void push( Object* obj ) {
that it can reuse its }
add( obj, 0 );

p
superclass for }

implementation
purposes only
Vector* v = new Stack( );
8
Stack* s = new Stack( ); 9
s->add( … ); 8
s->push( … ); 9
More on Inheritance COMPSCI 230 Software Design & Construction 6

More on Inheritance
Subclassing for limitation
„ This is similar to subclassing class Stack extends Vector {
f construction – typically
for ll public
bl void d push(
h( Object
Ob obj
b ){
// Always add to the start
where a library class is // of the vector.
reused as a convenience add( 0, obj );
}
means of implementing a new …
class public void add( int index, Object obj ) {
// Eliminate this method by throwing
„ With subclassing for // an unchecked exception.
limitation, the subclass throw new
pp p p
UnsupportedOperationException( ( );
)
overrides inherited }
behaviour that is }
inappropriate to eliminate it

Subclassing for limitation clearly contravenes the


principle of substitution, and should be avoided
More on Inheritance COMPSCI 230 Software Design & Construction 7

Subclassing for combination


„ It is sometimes useful to be Student Teacher

able
bl to define
d f a new class
l by
b enrol( ) teach( )

inheriting properties from


many superclasses; this is
known as multiple inheritance
Tutor
„ Multiple inheritance brings
with it complexity and is only
supported by a subset of
OOPLs e.g.
OOPLs, e g C++,
C++ Python Tutor instance

sonny : Tutor
enrol( )
teach( )
More on Inheritance COMPSCI 230 Software Design & Construction 8

More on Inheritance
Inheritance & instantiation
„ We know that a constructor 1: execute code
j
in Object’s
is always
l s executed
x cut d when
h n constructor
instantiating a class Object

„ Where inheritance is
involved, a constructor
method for each class in the
inheritance chain – between
the class being instantiated PlayingCard

and the root superclass 2: execute code


inclusive – is executed in PlayingCard’s
„ Constructor code is constructor
executed top-down the PlayingCard aCard = new PlayingCard( );
inheritance hierarchy

More on Inheritance COMPSCI 230 Software Design & Construction 9

Inheritance & non-default


constructors class Shape {
private int x, y;

// No default constructor.
„ Where a superclass has a
d f l constructor, it is
default public
bli Sh
Shape(( iint x, iint y ) {
this.x = x;
implicitly executed when this.y = y;
instantiating a subclass }
}
„ In cases where a superclass
doesn’t offer a default class TextShape extends Shape {
private String text;
constructor, the subclass
must provide arguments to public TextShape( int x, int y ) {
p ( x, y );
super( ) // Calls Shape’s
p constructor.
one of the superclass
superclass’ss text = null;
constructors }
„ In Java, the super keyword public TextShape( int x, int y, String text ) {
provides access to a class’s super( x, y ); // Calls Shape’s constructor.
superclass this.text = text;
}
}
More on Inheritance COMPSCI 230 Software Design & Construction 10

More on Inheritance
Inheritance & destruction /
finalization public class Logger {

private Writer writer;

public Logger( String logFile ) {


„ In C++, destructors are try {
writer = new FileWriter( logFile );
executed bottom-up } catch( … ) {
}
„ In Java, finalizers are }

less elegant public void log( String text ) {


/* Write out text. */
„ To ensure that a …
superclass’s finalize }
method is executed, an protected void finalize( ) {
explicit call to its finalize try {
method is necessary writer.close( );
} catch( IOException ) {
/* Ignore any error closing file. */
}
}
}

More on Inheritance COMPSCI 230 Software Design & Construction 11

Anonymous java.awt.event.WindowListener is an << interface >>

classes
interface that defines methods (7) WindowListener
concerning the lifecycle of a window
windowClosing( )

„ An anonymous class is one


that:
h java.awt.event.WindowAdapter
d d
WindowAdapter
implements the WindowListener
„ Has no name interface with empty method bodies
„ Is instantiated exactly
once
class Bounce extends JPanel {
„ Must either extend a …
named superclass or public Bounce( ) {
implement a named addWindowListener(
interface
nterface new WindowAdapter( ) {
public
l void d windowClosing(WindowEvent
d l ( d E e)) {
„ Has an implicit default System.exit( 0 );
constructor }
} To implement WindowListener
„ Anonymous classes are well ); behaviour, a common technique is
create an anonymous subclass of
suited to small tasks }
WindowAdapter and override the
}
method(s) of interest

More on Inheritance COMPSCI 230 Software Design & Construction 12

More on Inheritance
Static typing in OOPLs << abstract >>
Shape

move( ) : void
paint( ) : void

„ We know that with a


statically typed language like
Java, a variable is associated RectangleShape
with a type
„ The type imposes
restrictions on how a
variable can be used and
these restrictions are RectangleShape rect = new RectangleShape( );
checked at compile-time Shape shape = rect;

„ For object reference


variables,, the type
yp restricts: RectangleShape instance
„ the classes of object to
which the variable can refer shape : Shape
„ the messages that can be
move, paint
sent using the variable
move, paint
rect : RectangleShape

More on Inheritance COMPSCI 230 Software Design & Construction 13

Static vs dynamic typing Object

toString( )

„ A variable’s static class is fixed


at compile time but its dynamic
class may vary at run-time PlayingCard
„ As we’ve seen with the principle suit( )
of substitution, a reference rank( )
variable of type static class T
can refer to an instance of T or
to an instance of any of T’s Object anObject = new PlayingCard( );
subclasses
„ Through a reference variable of
static class type T, the set of Static type Dynamic type
messages that
th t can be
b sentt using
i
that variable are the methods
defined by T and its
superclasses

Is it possible in Java to send a message that


can’t be understood by the receiver object?
More on Inheritance COMPSCI 230 Software Design & Construction

More on Inheritance
Run-time type determination
„ Since an object reference can, in
general, point to many classes of Object
object, OOPLs offer a means to
determine what class of object a
reference
f n currentlyntl p
points
ints tto
„ Java provides the instanceof
operator << abstract >>
Shape
„ instanceof evaluates to true if the
left operand refers to an instance
of the class (or any of its
subclasses) identified by the right
hand operand, false otherwise
RectangleShape

Shape s = new RectangleShape( );

s instanceof Object => true


RectangleShapeWithText
s instanceof Shape => true

s instanceof RectangleShape => true

s instanceof RectangleShapeWithText => false


More on Inheritance COMPSCI 230 Software Design & Construction 15

Object

Casting
„ Casting is often Movie

necessary to access title : String


g

members specific to the getTitle( ) : String

object’s class

obj : Object ActionMovie DramaMovie


m : Movie

Movie instance

obj.getTitle( )
8 Movie m = ( Movie )obj;

compile-time error
m.getTitle( );
9
Casting does not change the object that is pointed to in any way.

Casting simply allows an object to be referred to by a reference variable of a


specified type.
More on Inheritance COMPSCI 230 Software Design and Construction 16

More on Inheritance
Casting
„ Casting is potentially „ To check that a
dangerous potential cast is safe,
Movie instance the instanceof operator
obj : Object
should be used
Movie m = ( Movie )obj; 9 Compile time
Object-ref instanceof Class

8 Run-time
obj : Object
A ClassCastException is thrown if the
type cast is incompatible with the type of
object to be pointed to. ActionMovie instance

E.g. Movie is the cast type – and given


Java’s typing rules we know that a obj instanceof ActionMovie => true
reference variable of type Movie can only
point to instances of Movie or to obj instanceof Movie => true
instances of Movie subclasses.
More on Inheritance COMPSCI 230 Software Design and Construction 17

Casting: compile-time checking m4 : ActionMovie

Object Movie
m : Movie ActionMovie instance
instance
m3 : Movie
m2 : Movie str : String String
DramaMovie instance
Movie String
instance
title : String
Compile-time Run-time
getTitle( ) : String behaviour behaviour

(ActionMovie)m; 9 9
(ActionMovie)str; 8
ActionMovie DramaMovie

(ActionMovie)m2; 9 8
Ref. var (ActionMovie)m3; 9 8
Cast-type
(Movie) m4; 9 9
At compile-time, checking is carried out to determine whether the cast-type and the
type
More of the existing reference
on Inheritance COMPSCIvariable are Design
230 Software related through
and inheritance.
Construction 18

More on Inheritance
Casting: run-time checking m4 : ActionMovie

Object Movie
m : Movie ActionMovie instance
instance
m3 : Movie
m2 : Movie str : String String
DramaMovie instance
Movie String
instance
title : String
Compile-time Run-time
getTitle( ) : String behaviour behaviour

(ActionMovie)m; 9 9
(ActionMovie)str; 8
ActionMovie DramaMovie

(ActionMovie)m2; 9 8
Ref. var (ActionMovie)m3; 9 8
Cast-type
(Movie) m4; 9 9
At run time, a check is made to determine whether the object actually pointed to is
compatible with the cast-type.
More on Inheritance COMPSCI 230 Software Design and Construction 19

More on Inheritance

Potrebbero piacerti anche