© 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing...

download © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

of 28

  • date post

  • Category


  • view

  • download


Embed Size (px)

Transcript of © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing...


    Declaring Interfaces

    Implementing Interfaces

    Using Interfaces Polymorphically

    Visibility Modifiers


  • BouncingBalls and CSMobiles

    A BouncingBall and a CSMobile are very different

    But there are some things that both can do

    BouncingBalls and CSMobiles can have a mutable colortheir color can be queried for and changed (by using accessors and mutators like we saw before)

    But they certainly dont inherit from a common superclass

    How do we model similarities in objects that are inherently different?


  • InterfacesMuch like two objects are related if they inherit from the same superclass, objects can be related if they implement the same interface

    Superclasses factor out responsibilities among similar classes that model is-a hierarchy

    Interfaces are mainly used to factor out responsibilities among very different classes whose only commonality are specific shared capabilitiesmodels the acts-as relationship

    For example, both BouncingBall and CSMobile might implement the wheels.Colorable interfacethey both act as Colorablesobjects that have the capability to have a color


  • More InterfacesInterfaces only declare capabilities that object must have there are no definitionsno code! (except declarations)

    Similar to abstract classes with all methods abstract, exceptno constructorusually no instance variableslist of responsibilities (public methods) and nothing else

    Interfaces prescribe very generic rolesprofessors, TAs and tutors all teach as part of their responsibility but they come from different class hierarchies and teach in different ways

    Interface names are often adjectives, ending in -able or -ive.examples: Colorable, Rotatable

    Interface names that specify roles often end in -erexamples: Container, Mover, Teacher

    What might a Colorable interface look like?


  • Colorable Interface Syntaxpackage wheels; // Short for training wheels

    /** * This interface models something * with a changeable color. It * specifies that all classes * implementing it can have their * color set and accessed. */

    public interface Colorable {

    // set the color of the implementing object public void setColor(java.awt.Color c);

    // get the color of the implementing // object public java.awt.Color getColor();

    }Note the semicolons!


  • Colorable Interface Syntax Explainedpublic interface Colorable {declaration for an interfacesame as for class, except interface instead of class

    public void setColor(java.awt.Color c);specifies that anything that is Colorable must have the capability to have its color set

    public java.awt.Color getColor();specifies that anything that acts as a Colorable must have the capability to give access to its color

    Note simplicity of methodsColorable interface only specifies accessor and mutator for Colormethods can only be abstract, so that keyword can be left offmethods can only be public, but we leave that keyword in for the sake of clarity

    Thats it!interfaces are really simple!in fact, this is almost verbatim the code in the actual wheels.Colorable interfacewheels is a support package (shorthand for training wheels) used in the textbook

    Note that there is no code and hence no code sharing with interfaces - it is purely a contractual mechanism that puts all implementation responsibilities on the implementors


  • Implementing InterfacesClasses can extend one other class

    Classes can implement any number of interfaces

    Can extend a superclass and implement interfaces

    The Car, for example, could implement interfaces which categorize objects that are able to move, hold passengers, be driven, be repaired, etc.

    Interfaces thus create the fourth mechanism for factoring which is even more general and flexible than othersclasses and instancesmethods with parameterssuperclasses and subclassesinterfaces and implementations


  • Implementing Interfaces: Syntax

    /** * This class models a CSMobile * that implements the Colorable * interface. */

    public class CSMobile extends Car implements Colorable {

    private java.awt.Color _color;

    // other instance variables

    // constructor(s)

    public void setColor( java.awt.Color c ) { _color = c; }

    public java.awt.Color getColor() { return _color; } // other methods}


  • Interface Syntax Explainedpublic class CSMobile extends Car implements Colorable {CSMobile extends Car but also implements Colorableimplementing an interface is as simple as using the word implementsto implement multiple interfaces, just separate them by a commae.g., implements Colorable, Locatable, Mover

    CSMobile defines Cars interface methods by making them simple accessors and mutatorscould also do something more complicatedJava doesnt care how you define the methods of an interface, just that you do define them

    What happens if you dont define a method of an interface you implement?same thing that happens if you dont define an abstract method of a superclassclass must be declared abstract


  • Using Interfaces PolymorphicallyInterfaces can be used as types of variables and parameters, just like classese.g., CSMobile can be referenced polymorphically as CSMobile, Car, and Colorableyou can even declare an instance or local variable as an interfacee.g., Colorable myColorable;

    Methods which accept parameters of interface typedont care what actual class of object will bedo care that object responds to messages declared in interfacedont care how the object responds to those messages

    Using interfaces polymorphically as parameter types produces maximum run-time flexibility because it allows use of classes which implement same interface interchangeably at run-time

    The downside is that the code using the parameter can only use the behaviors of the interface - none of the specialized behaviors of the implementing classes may be used


  • More Polymorphism in InterfacesMany classes implement the same interface

    The CSMobile implements the Colorable interface

    All wheels.users.RectangularShapes implement the Colorable interface

    Therefore, both the CSMobile and wheels.users.RectangularShape can be treated as Colorables

    How would we code this?


  • PaintShop Syntax/** * This class models a shop that can * apply a random Color to any object that is * Colorable. */

    public class PaintShop {

    public PaintShop() {}

    public void randomPaintJob( wheels.Colorable colorable ) { java.awt.Color rColor = this.getRandomColor();

    colorable.setColor(rColor); }

    // other methods} Here PaintShop relies on any implementor of its Colorable interface having a setColor() method without caring how that is done


  • PaintProgram Syntax/** * This class demonstrates the use * of polymorphism with interfaces. */

    public class PaintProgram {

    private CSMobile _csMobile;private wheels.users.Rectangle _rect; private PaintShop _paintshop;

    public PaintProgram() { _csMobile = new CSMobile(); _rect = new wheels.users.Rectangle(); _paintshop = new PaintShop(); this.paint(); }

    public void paint() { _paintShop.randomPaintJob(_csMobile); _paintShop.randomPaintJob(_rect); }



  • PaintShop/PaintProgram Syntaxpublic void randomPaintJob(wheels.Colorable colorable)randomPaintJob has parameter representing the wheels.Colorable it is working onthis could be a CSMobile, a wheels.users.Rectangle, or anything else that implements the wheels.Colorable interface

    Colorable.setColor(rColor);calls setColor() method of current wheels.Colorablebecause colorable implements the Colorable interface, it must have a setColor methoddont care what actual type of actual parameter of colorable is_paintShop.randomPaintJob( wheels.Colorable colorable);because CSMobile acts as a wheels.Colorable, randomPaintJob can be called with _csMobile as a parameterwhen randomPaintJob is called, it will set the color of the CSMobile to a random colorthe same thing applies for _rect which is a wheels.users.Rectangle and acts as a wheels.ColorableNote: Cars and Shapes may implement setColor() in very different ways!


  • Interfaces, Inheritance, ExtensibilityLike classes, interfaces can extend other interfaces

    Unlike classes, interfaces can extend any number of other interfacesthis is because interfaces merely declare policy they never specify any implementationjust put a comma between interface names after extends

    Extending multiple interfaces is useful for objects that have some things in common but otherwise behave very differentlyexample: GUI components (e.g., PushButton, TextBox, Menu)they all behave and react very differentlybut they all have the capability to be located on the screen and sizedso a Component interface is created that extends both Locatable and Sizeable

    Remember: objects inherit all capabilities from their superclasses, so an object inherits all interfaces from its superclasstherefore if a superclass implements an interface, the subclass implements it too!


  • Implementing Multiple InterfacesImplementing multiple interfaces is easyJust implement the union of all their methods!

    public interface Mover { public void move();} public interface Shaker } public void shake();}

    public class Politician implements Mover, Shaker {

    //constructor public void move() { //code to move} public void shake() { //code