More on Inheritance Interfaces & Abstract Classes
Java interfaces A Java interface is used to specify minimal functionality that a client requires of a server. A Java interface contains: method specifications named constant definitions. A Java interface does not contain: constructors, method bodies, instance variables.
interface definition interface InterfaceName { constant definitions } method declarations (without implementations). A method declaration is simply an access modifier, a return type, and a method signature followed by a semicolon. No objects can be constructed from it. Objects can be constructed from a class that implements an interface.
Example public interface MyInterface { public static final int aconstant = 32; public static final double pi = 3.14159; } public void methoda( int x ); public double methodb();
interface definition A class implements an interface by doing this: public class SomeClass implements interfacename { // fields, methods and constructors } // implementation of interface methods A class may implement several interfaces.
Notes A class that implements an interface must implement each method in the interface. Methods from the interface must be declared public in the class. Constants from the interface can be used as if they had been defined in the class. Constants should not be redefined in the class.
Modeling alternative implementations A game implementation models class Player responsible for making a move according to Game rules. Strategies Player can implement when making a move: Timid strategy Greedy strategy Clever strategy
Modeling alternative implementations Player abstraction and Player clients should be independent of implementations; independent of strategies chosen; implementations must respect the abstraction s contract: Player makes a move according to Game rules.
Java Interface <<Interface>> Player TimidPlayer GreedyPlayer CleverPlayer
Interface and types An interface defines a type. if it references an instance of a class that implements the interface. A value of type TimidPlayer, is also of type Player. A value of type GreedyPlayer, is also of type Player. A value of type CleverPlayer is also of type Player.
Interface and types The type TimidPlayer is said to be a subtype of the type Player. The type GreedyPlayer is said to be a subtype of the type Player. The type CleverPlayer is said to be a subtype of the type Player Player is a supertype of TimidPlayer. GreadyPlayer. CleverPlayer.
Interface and types A type defined by an interface can be used like any other reference type. It can be the type of an instance variable or parameter, It can be the return type of a query
Types and Subtypes If client expects server of type Player, then a value of any Player subtype can be provided. Subtype rules: if type A is a subtype of type B, then an A value can be provided wherever a B value is required. an A expression can be written wherever a B value is required
Example Consider a Game class with constructor: public Game (Player player1, Player player2) It can be invoked with arguments referencing TimidPlayers, GreedyPlayers, CleverPlayers. i.e player1 and/or player2 may be any of the subtypes
Static types The Game method nextplayer is specified as public Player nextplayer () If game is a Game instance, Player is the static type of expression game.nextplayer()
Dynamic types When game.nextplayer() is evaluated during execution, value returned will reference an specific object: If an instance of TimidPlayer. Then dynamic type of value returned by expression is TimidPlayer. If an instance of GreedyPlayer. Then dynamic type of value returned by expression is GreedyPlayer. If an instance of CleverPlayer. Then dynamic type of value returned by the expression is CleverPlayer. The dynamic type is always a subtype of Player.
Types and Subtypes Given private Player nextplayer; private void reportplay (Player player) public Player winner () The following require expressions of type Player nextplayer = Player expression required; reportplay( Player expression required); public Player winner () { return Player expression required;
Types and Subtypes Given TimidPlayer timid = newtimidplayer( Fred"); The following are legal nextplayer = timid; reportplay(timid); public Player winner () { return timid; }
Types and Subtypes If game is a Game instance, we cannot write the following TimidPlayer next = game.nextplayer(); Assignment operator requires a TimidPlayer on the right. game.nextplayer() is of type Player, and Player is not a subtype of TimidPlayer.
Review of Player interface <<Interface>> Player TimidPlayer GreedyPlayer CleverPlayer Interface Player implemented by several classes classes are identical except for implementation of taketurn. classes contain considerable amount of duplicate code.
Abstract classes AbstractPlayer <<Interface>> Player can contain implementations of methods common to all Player variants, Player subclasses inherit these methods. AbstractPlayer TimidPlayer GreedyPlayer CleverPlayer
Abstract classes An abstract class is a class: Defines a type. Occupies a position in the class hierarchy. Can be the parent of other classes, abstract or not. Has a unique parent which may or may not be abstract. Has one or more constructors. It can define nonabstract methods. It can contain abstract methods, Has instance variables. It cannot be instantiated. Concrete class: a non-abstract class.
Abstract class definition public abstract class ClassName {..... // definitions of methods and variables }
Abstract Methods An abstract method has no body. (It has no statements.) It declares an access modifier return type method signature followed by a semicolon. A non-abstract child class inherits the abstract method and must define a nonabstract method that matches the abstract method
Example public abstract class Item { } // fields as before // then methods public abstract void foomethod(int x) ; Each non-abstract class that extends Item must provide an implementation for foo
Example public abstract class AbstractPlayer implements Player { } private String name; // other attributes public AbstractPlayer (String name) { } public String name () { } // other fully defined methods public String tostring () { } public abstract void taketurn (Move move) ;
TimidPlayer definition class TimidPlayer extends AbstractPlayer { public TimidPlayer (String name) { super(name); } public void taketurn (Move move) { // details of the method } }
Interfaces, abstract classes and concrete classes An interface used to specify functionality required by a client. An abstract class provides a basis on which to build concrete servers. A concrete class completes server implementation specified by an interface; furnish run-time objects; not generally suited to serve as a basis for extension.
Abstract class use An abstract class factors out implementation of its concrete subclasses. Used to exploit polymorphism. Functionality specified in parent class can be given implementations appropriate to each concrete subclass. Abstract class must be stable. any change in an abstract class propagates to subclasses and their clients. A concrete class can only extend one (abstract) class
Interface use Interfaces are by definition abstract. separate an object s implementation from its specification. they do not fix any aspect of an implementation. A class can implement more than one interface. Interfaces allow a more generalized use of polymorphism; instances of relatively unrelated classes can be treated as identical for some specific purpose.
Composition Uses of composition a component is an intrinsic part of an object. a class formed as an aggregation of components, where components exist independently of aggregation. to wrap an existing class in order to alter its interface.
Class extension OR class composition? «interface» Player AbstractPlayer TimidPlayer GreedyPlayer CleverPlayer Player has-a «interface» PlayStrategy TimidStrategy GreedyStrategy CleverStrategy
public class Player { private String name; private PlayerStrategy strategy; // other attributes public AbstractPlayer (String name) { } public String name () { } // other fully defined methods public String tostring () { } } public void taketurn () { strategy.makemove(); }
Class extension v.s. class composition Two advantages of class extension code reuse polymorphism. Disadvantages of class extension Changes to a superclass specification propagate to clients and subclasses classes are not always designed and documented for extension. a subclass is committed to maintain specifications inherited from its superclass.
Class extension v.s. class composition Advantages of composition Existing classes can be used in composed classes. Can change object s behavior dynamically. Supports stronger encapsulation than does inheritance. Can change specification of composed class without changing core. Composed class depends only on specification of core class, not on its implementation. Implementation changes in core class do not propagate to composed class.