abstract classes and interfaces

Post on 05-Jan-2016

16 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

its a topic of java helps you understanding abstract classes and interfaces

TRANSCRIPT

Abstract Classes & Interfaces

Electrical Engineering Department –NFC IET Multan

Abstract Cla s se s and Inte rface s

The objectives of this chapte r a re :

•To explore the concept of abs tract cla sses

•To unders tand inte rfaces•To unders tand the importance of both.

What is an Abstract cla s s?

•Supercla sses a re created through the process ca lled"genera lization"• Common fea tures (methods or variables) a re factored out of object

classifica tions (ie . classes).• Those fea tures are formalized in a class. This becomes the superclass• The classes from which the common fea tures were taken become

subclasses to the newly crea ted super class

•Often, the supercla ss does not have a "meaning" or does notdirectly re la te to a "thing" in the rea l world•It is an a rtifact of the genera lization process

•Because of this , abs tract cla sses cannot be ins tantia ted• They act as place holders for abstraction

Vehicle- make: String- model: String- tireCount: int

Car- trunkCapacity: int

Abstract superclass:

Abstract Cla s s Example

•In the following example , the subclasses represent objectstaken from the problem domain.

•The supercla ss represents an abs tract concept tha t does notexis t "as is" in the rea l world.

Truck- bedCapacity: int

Note: UMLrepresents abstractclasses by displaying their namein italics.

What Are Abstract Cla s se s Used For?

•Abstract cla sses a re used heavily in Des ign Pa tte rns• Crea tiona l Pa tte rns: Abstract class provides inte rface for crea ting

objects. The subclasses do the actua l object crea tion• Structura l Pa tte rns: How objects a re structured is handled by an

abstract class. What the objects do is handled by the subclasses• Behavioura l Pa tte rns: Behavioura l inte rface is decla red in an abstract

superclass. Implementa tion of the inte rface is provided by subclasses.

•Be careful not to over use abs tract cla sses•Every abs tract cla ss increases the complexity of your des ign• Every subclass increases the complexity of your design• Ensure tha t you rece ive acceptable re turn in te rms of functiona lity given

the added complexity.

Defining Abstract Cla s se s

•Inheritance is decla red us ing the "extends" keyword• If inheritance is not defined, the class extends a class ca lled Object

p u b l i c a b s t r a c t c l a s s V e h i c l e

{

p r i v a t e S t r i n g m a k e ;

p r i v a t e S t r i n g m o d e l ;

p r i v a t e i n t t i r e C o u n t ;

[ . . . ]

p u b l i c c l a s s C a r e x t e n d s V e h i c l e

{

p r i v a t e i n t t r u n k C a p a c i t y ;

[ . . . ]

Vehicle- make: String- model: String- tireCount: int

Car- trunkCapacity: int

Truck- bedCapacity: int

p u b l i c c l a s s T r u c k e x t e n d s V e h i c l e

{

p r i v a t e i n t b e d C a p a c i t y ;

[ . . . ]

Often referred to as "concrete" classes

Abstract Me thods

•Methods can a lso be abs tracted• An abstract method is one to which a signa ture has been provided, but

no implementa tion for tha t method is given.• An Abstract method is a placeholder. It means tha t we decla re tha t a

method must exist, but there is no meaningful implementa tion for tha tmethods within this class

•Any class which contains an abs tract me thod MUST also beabs tract•Any class which has an incomple te method definition cannot

be ins tantia ted (ie . it is abs tract)

•Abstract cla sses can contain both concre te and abs tractme thods .• If a method can be implemented within an abstract class, and

implementa tion should be provided.

Abstract Me thod Example

•In the following example , a Transaction's va lue can becomputed, but the re is no meaningful implementa tion tha t canbe defined within the Transaction class .• How a transaction is computed is dependent on the transaction's type• Note: This is polymorphism.

Transaction- computeValue(): int

RetailSale- computeValue(): int

StockTrade- computeValue(): int

Defining Abstract Me thods

•Inheritance is decla red us ing the "extends" keyword• If inheritance is not defined, the class extends a class ca lled Object

p u b l i c a b s t r a c t c l a s s T r a n s a c t i o n

{

p u b l i c a b s t r a c t i n t c o m p u t e V a l u e ( ) ;

p u b l i c c l a s s R e t a i l S a l e e x t e n d s T r a n s a c t i o n

{

p u b l i c i n t c o m p u t e V a l u e ( )

{

[ . . . ]

Transaction- computeValue(): int

RetailSale- computeValue(): int

StockTrade- computeValue(): int

p u b l i c c l a s s S t o c k T r a d e e x t e n d s T r a n s a c t i o n

{

p u b l i c i n t c o m p u t e V a l u e ( )

{

[ . . . ]

Note: no implementation

What is an Inte rface?

•An inte rface is s imila r to an abs tract cla ss with the followingexceptions :• All methods defined in an inte rface are abstract. Inte rfaces can conta in

no implementa tion• Inte rfaces cannot conta in instance variables. However, they can conta in

public sta tic fina l variables (ie . constant class variables)

•Inte rfaces a re decla red us ing the "inte rface" keyword•If an inte rface is public, it mus t be contained in a file which

has the same name .

•Inte rfaces a re more abs tract than abs tract cla sses

•Inte rfaces a re implemented by classes us ing the "implements"keyword.

Declaring an Inte rface

p u b l i c i n t e r f a c e S t e e r a b l e

{

p u b l i c v o i d t u r n L e f t ( i n t d e g r e e s ) ;

p u b l i c v o i d t u r n R i g h t ( i n t d e g r e e s ) ;

}

In Steerable.java:

p u b l i c c l a s s C a r e x t e n d s V e h i c l e i m p l e m e n t s S t e e r a b l e

{

p u b l i c i n t t u r n L e f t ( i n t d e g r e e s )

{

[ . . . ]

}

p u b l i c i n t t u r n R i g h t ( i n t d e g r e e s )

{

[ . . . ]

}

In Car.java:

When a class "implements" aninterface, the compiler ensures thatit provides an implementation forall methods defined within theinterface.

Implementing Inte rface s

•A Class can only inhe rit from one supercla ss . However, acla ss may implement seve ra l Inte rfaces• The inte rfaces tha t a class implements are separa ted by commas

•Any class which implements an inte rface must provide animplementa tion for a ll me thods de fined within the inte rface .• NOTE: if an abstract class implements an inte rface , it NEED NOT

implement a ll methods defined in the inte rface . HOWEVER, eachconcre te subclass MUST implement the methods defined in theinte rface .

•Inte rfaces can inhe rit me thod s igna tures from otherinte rfaces .

Declaring an Inte rface

p u b l i c c l a s s C a r e x t e n d s V e h i c l e i m p l e m e n t s S t e e r a b l e , D r i v e a b l e

{

p u b l i c i n t t u r n L e f t ( i n t d e g r e e s )

{

[ . . . ]

}

p u b l i c i n t t u r n R i g h t ( i n t d e g r e e s )

{

[ . . . ]

}

/ / i m p l e m e n t m e t h o d s d e f i n e d w i t h i n t h e D r i v e a b l e i n t e r f a c e

In Car.java:

Inhe riting Inte rface s

•If a supercla ss implements an inte rface , it's subclasses a lsoimplement the inte rface

p u b l i c a b s t r a c t c l a s s V e h i c l e i m p l e m e n t s S t e e r a b l e

{

p r i v a t e S t r i n g m a k e ;

[ . . . ]

p u b l i c c l a s s C a r e x t e n d s V e h i c l e

{

p r i v a t e i n t t r u n k C a p a c i t y ;

[ . . . ]

Vehicle- make: String- model: String- tireCount: int

Car- trunkCapacity: int

Truck- bedCapacity: int

p u b l i c c l a s s T r u c k e x t e n d s V e h i c l e

{

p r i v a t e i n t b e d C a p a c i t y ;

[ . . . ]

Multiple Inhe ritance?

•Some people (and textbooks) have sa id tha t a llowing classesto implement multiple inte rfaces is the same thing as multipleinhe ritance

•This is NOT true. When you implement an inte rface :• The implementing class does not inherit instance variables• The implementing class does not inherit methods (none are defined)• The Implementing class does not inherit associa tions

•Implementa tion of inte rfaces is not inhe ritance . An inte rfacede fines a lis t of me thods which must be implemented.

Inte rface s a s Types

•When a class is de fined, the compile r views the class as anew type .

•The same thing is true of inte rfaces . The compile r regards aninte rface as a type .• It can be used to decla re variables or method parameters

i n t i ;

C a r m y F l e e t [ ] ;

S t e e r a b l e a n o t h e r F l e e t [ ] ;

[ . . . ]

m y F l e e t [ i ] . s t a r t ( ) ;

a n o t h e r F l e e t [ i ] . t u r n L e f t ( 1 0 0 ) ;

a n o t h e r F l e e t [ i + 1 ] . t u r n R i g h t ( 4 5 ) ;

Abstract Cla s se s Versus Inte rface s

•When should one use an Abstract cla ss ins tead of aninte rface?• If the subclass-superclass re la tionship is genuine ly an "is a" re la tionship.• If the abstract class can provide an implementa tion a t the appropria te

leve l of abstraction

•When should one use an inte rface in place of an AbstractClass?• When the methods defined represent a small portion of a class• When the subclass needs to inherit from another class• When you cannot reasonably implement any of the methods

Abstract Classes

19

Abstract Classes

§ Java allows abstract classes

– use the modifier a b s t r a c t on a class header to declare anabstract classa b s t r a c t c l a s s V e h i c l e

{ … }

" An abstract class is a placeholder in a class hierarchy thatrepresents a generic concept

Vehicle

Car Boat Plane

20

Abstract Class: Example

p u b l i c a b s t r a c t c l a s s V e h i c l e

{

S t r i n g n a m e ;

p u b l i c S t r i n g g e t N a m e ( )

{ r e t u r n n a m e ; } \ \ m e t h o d b o d y

a b s t r a c t p u b l i c v o i d m o v e ( ) ;

\ \ n o b o d y !

}

§ An abstract class often contains abstract methods,though it doesn’t have tom Abs tract methods cons is t of only methods declara tions ,

without any method body

21

Abstract Classes" An abstract class often contains abstract methods, though it

doesn’t have to

– Abstract methods consist of only methods declarations, without anymethod body

" The non-abstract child of an abstract class must override theabstract methods of the parent

" An abstract class cannot be instantiated

(why?)

" The use of abstract classes is a design decision; it helps usestablish common elements in a class that is too general toinstantiate

Referencing Objects

23

Recap: Object References" All inte raction with an object occurs through

object re fe rence variables

" An object re fe rence variable holds there fe rence (address , the loca tion) of anobject

Ches s Piece bis hop1 = new Ches s Piece();

b i s h o p 1

24

Recap: Primitive Assignment

" The act of assignment takes a copy of a value andstores it in a variable

" For primitive types:

n u m 2 = n u m 1 ;

Before

n u m 1

5

n u m 2

12

After

n u m 1

5

n u m 2

5

25

Recap: Reference Assignment

" For object references, the reference is copied:

b i s h o p 2 = b i s h o p 1 ;

Before

b i s h o p 1 b i s h o p 2

After

b i s h o p 1 b i s h o p 2

26

Recap: Relationship Between Objects andObject References

" Two or more references can refer to the sameobject; these references are called aliases of eachother

" One object (and its data) can be accessed usingdifferent references

27

References and Inheritance

" An object reference can refer to an object of itsclass, or to an object of any class derived from it byinheritance

" For example, if the H o l i d a y class is used toderive a child class called C h r i s t m a s , then aH o l i d a y reference could actually be used topoint to a C h r i s t m a s object

H o l i d a y d a y ;

d a y = n e w H o l i d a y ( ) ;

…d a y = n e w C h r i s t m a s ( ) ;

Holiday

Christmas

28

References and Inheritance" Assigning an object to an ancestor reference is considered to be

a widening conversion, and can be performed by simpleassignment

" Assigning an ancestor object to a reference can also be done,but it is considered to be a narrowing conversion and must bedone with a cast

" The widening conversion is the most useful

– for implementing polymorphism

H o l i d a y d a y = n e w C h r i s t m a s ( ) ;

C h r i s t m a s c 1 = n e w C h r i s t m a s ( ) ;

H o l i d a y d a y = c 1 ;

C h r i s t m a s c 2 = ( C h r i s t m a s ) d a y ;

Referencing and Inheritance

30

Recap: References and Inheritance

" An object reference variable can refer to anyobject instantiated from

– its own class, or

– any class derived from it by inheritance

" For example,H o l i d a y d a y ;

d a y = n e w H o l i d a y ( ) ;

…d a y = n e w C h r i s t m a s ( ) ;

Holiday

Christmas The assignment of an objectof a derived class to a

reference variable of thebase class can be considered

as a widening conversion

31

References and Inheritance

" Through a given type of reference variable, we caninvoke only the methods defined in that type

Can we do the following statements:d a y . c e l e b r a t e ( ) ;

d a y . l i s t e n T o C h r i s t m a s S o n g s ( ) ;

H o l i d a y d a y ;

d a y = n e w C h r i s t m a s ( ) ;

c l a s s H o l i d a y

{

p u b l i c v o i d c e l e b r a t e ( )

{ …}

}

c l a s s C h r i s t m a s e x t e n d s H o l i d a y

{

p u b l i c v o i d c e l e b r a t e ( )

{ …}

p u b l i c v o i d l i s t e n T o C h r i s t m a s S o n g s ( )

{ …}

}

32

References and Inheritance

" We can “promote”an object back to its originaltype through an explicit narrowing cast:

H o l i d a y d a y = n e w C h r i s t m a s ( ) ;

d a y . c e l e b r a t e ( ) ;

C h r i s t m a s c = ( C h r i s t m a s ) d a y ;

c . l i s t e n T o C h r i s t m a s S o n g s ( ) ;

Question: which celebrate() will be invoked by the line:day.celebrate();

Polymorphism

34

What is Polymorphism?

" Apolymorphic reference can refer to different types ofobjects at different times

– In java every reference can be polymorphic except of references tobase types and final classes.

" It is the type of the object being referenced, not thereference type, that determines which method is invoked

– Polymorphic references are therefore resolved at run-time, notduring compilation; this is called dynamic binding

" Careful use of polymorphic references can lead to elegant,robust software designs

35

Polymorphism" Polymorphism: A polymorphic reference v is declared as class C, but unless

C is final or base type, v can refer to an object of class C or to an object ofany class derived from C.

" A method call v.<method_name>(<args>) invokes a method of the class ofan object referred to by v (not necessarily C):

" A very common usage of polymorphism: If classes C1, C2, ...., Cn are allderived from C, define an array A of elements of C.

The entries A[i] can then refer to objects of classes C1, ...., Cn.

E x 1 :

H o l i d a y d a y =

n e w C h r i s t m a s ( ) ;

d a y . c e l e b r a t e ( ) ;

E x 2 :

v o i d p r o c e s s ( H o l i d a y d a y )

{ …d a y . c e l e b r a t e ( ) ;

… }

C h r i s t m a s d a y = . . . ;

p r o c e s s ( d a y )

36

StaffMember# name : String# address : String# phone : String+ toString() : String+ pay() : double

Volunteer

+ pay() : double

Employee

# socialSecurityNumber : String# payRate : double

+ toString() : String+ pay() : double

Executive

- bonus : double

+ awardBonus(execBonus : double) : void+ pay() : double

Hourly

- hoursWorked : int

+ addHours(moreHours : int) : void+ toString() : String+ pay() : double

- staffList: staffMemeber[]

Staff

+ payday() : void

- staffList : StaffMemeber[]

The pay-roll of a firm

Method payday() alsocalls println(s) on eachs.

This works becauseprintln is defined as:v o i d p r i n t l n ( O b j e c t o )

{ S t r i n g s = o . t o S t r i n g ( ) ) ;

O u t S t r e a m . o u t ( s ) ;

}

Method payday()iterates over elementss of staffList and callss.pay() on each s.

37

Single vs. Multiple Inheritance

" Some object-oriented languages allow multiple inheritance,which allows a class to be derived from two or more classes,inheriting the members of all parents

" The price: collisions, such as the same variable name, samemethod name in two parents, have to be resolved

" Java decision: single inheritance, meaning that a derived classcan have only one parent class

Interfaces

39

Java Interface

" AJava interface is a collection of constants andabstract methods

– abstract method: a method header without a methodbody; we declare an abstract method using themodifier a b s t r a c t

– since all methods in an interface are abstract, thea b s t r a c t modifier is usually left off

" Methods in an interface have public visibility bydefault

40

Interface: Syntax

p u b l i c i n t e r f a c e D o a b l e

{

p u b l i c s t a t i c f i n a l S t r i n g N A M E ;

p u b l i c v o i d d o T h i s ( ) ;

p u b l i c i n t d o T h a t ( ) ;

p u b l i c v o i d d o T h i s 2 ( f l o a t v a l u e ,

c h a r c h ) ;

p u b l i c b o o l e a n d o T h e O t h e r ( i n t n u m ) ;

}

iinntteerrffaaccee iiss aa rreesseerrvveedd wwoorrdd

NNoo mmeetthhoodd iinn aanniinntteerrffaaccee hhaass aa ddeeff iinniittiioonn ((bbooddyy))

AA sseemmiiccoolloonn iimmmmeeddiiaatteellyyffoolllloowwss eeaacchh mmeetthhoodd hheeaaddeerr

41

Implementing an Interface

" Aclass formally implements an interface by

– stating so in the class header in the i m p l e m e n t s

clause

– a class can implement multiple interfaces: the interfacesare listed in the implements clause, separated bycommas

" If a class asserts that it implements an interface, itmust define all methods in the interface or thecompiler will produce errors

42

Implementing Interfacesp u b l i c c l a s s S o m e t h i n g i m p l e m e n t s D o a b l e

{

p u b l i c v o i d d o T h i s ( )

{

/ / w h a t e v e r

}

p u b l i c v o i d d o T h a t ( )

{

/ / w h a t e v e r

}

/ / e t c .

}

iimmpplleemmeennttss iiss aarreesseerrvv eedd wwoorrdd

EEaacchh mmeetthhoodd lliisstteeddiinn DDooaabbllee iiss

ggiivveenn aa ddeeff iinniittiioonn

p u b l i c c l a s s M a n y T h i n g s i m p l e m e n t s D o a b l e , A n o t h e r D o a b l e

43

Interfaces: An Example

" Aclass that implements an interface canimplement other methods as well

44

<<interface>>Complexity

+ getComplexity () : int+ setComplexity (int) : void

Question

+ getQuestion () : String+ getAnswer () : String+ answerCorrect (String) : boolean+ toString() : String

MiniQuiz

+ main(args : String[]) : void1

2

UMLDiagram

45

Interfaces: Examples fromJava Standard Class Library

" The Java Standard Class library defines many interfaces:

– the I t e r a t o r interface contains methods that allow the user tomove through a collection of objects easily

" h a s N e x t ( ) , n e x t ( ) , r e m o v e ( )

– the C o m p a r a b l e interface contains an abstract method calledc o m p a r e T o , which is used to compare two objects

i f ( o b j 1 . c o m p a r e T o ( o b j 2 ) < 0 )

S y s t e m . o u t . p r i n t l n ( “o b j 1 i s l e s s t h a n o b j 2 ”) ;

46

Polymorphism via Interfaces

" Define a polymorphism reference through interface

– declare a reference variable of an interface typeD o a b l e o b j ;

– the o b j reference can be used to point to any object of any classthat implements the D o a b l e interface

– the version of d o T h i s depends on the type of object that o b j isreferring to:

o b j . d o T h i s ( ) ;

47

Example: Polymorphism via Interface

" The payroll program revisited: we want to sort theemployees by name

48

More Examples

p u b l i c i n t e r f a c e S p e a k e r

{ p u b l i c v o i d s p e a k ( ) ;

}

c l a s s P h i l o s o p h e r e x t e n d s H u m a n

i m p l e m e n t s S p e a k e r

{ / /

p u b l i c v o i d s p e a k ( )

{ …}

p u b l i c v o i d p o n t i f i c a t e ( )

{ …}

}

c l a s s D o g e x t e n d s A n i m a l

i m p l e m e n t s S p e a k e r

{ / /

p u b l i c v o i d s p e a k ( )

{ …

}

}

S p e a k e r g u e s t ;

g u e s t = n e w P h i l o s o p h e r ( ) ;

g u e s t . s p e a k ( ) ;

g u e s t = D o g ( ) ;

g u e s t . s p e a k ( ) ;

S p e a k e r s p e c i a l ;

s p e c i a l = n e w P h i l o s o p h e r ( ) ;

s p e c i a l . p o n t i f i c a t e ( ) ;

S p e a k e r s p e c i a l ;

s p e c i a l = n e w P h i l o s o p h e r ( ) ;

( ( P h i l o s o p h e r ) s p e c i a l ) . p o n t i f i c a t e ( ) ;

// compiler error

49

Interface Hierarchies

" Inheritance can be applied to interfaces as well as classes

" One interface can be used as the parent of another

" The child interface inherits all abstract methods of the parent

" Aclass implementing the child interface must define allmethods from both the parent and child interfaces

" Note that class hierarchies and interface hierarchies aredistinct (they do not overlap)

top related