06 interfaces[1]

Upload: jaydeep-chauhan

Post on 10-Apr-2018

228 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 06 Interfaces[1]

    1/27

    September 21, 2006Interfaces 1 of 27

    INHERITANCE 2 & INTERFACES

    Partial Overriding

    Pseudo Inheritance

    Visibility Modifiers

    Garbage Collection

    Declaring Interfaces

    Implementing Interfaces

  • 8/8/2019 06 Interfaces[1]

    2/27

    September 21, 2006Interfaces 2 of 27

    Inherit This!

    5 things you might find in an Inheritance Hierarchy:

    1) superclass is too general to declare all

    behavior, so each subclass adds its own

    behavior

    2) superclass legislates an abstract behavior and

    therefore delegates implementation tosubclasses

    3) superclass specifies behavior, subclasses

    inherit behavior

    4) superclass specifies behavior, subclasses canchoose to override behavior- subclass can choose to reject its superclass

    implementation of any method and do it my way

    5) superclass specifies behavior, subclasses can

    choose to override behavior in part- called partial overriding

  • 8/8/2019 06 Interfaces[1]

    3/27

    September 21, 2006Interfaces 3 of 27

    Send in the Clowns: Partial Overriding (1 of 3)

    /**

    * Models a version of the CS15Mobile that

    * holds clowns in order to demonstrate new

    * idea: partial overriding.

    */

    public class CrazyCS15Mobile extends CS15Mobile {

    private BandOfClowns _clowns;

    public CrazyCS15Mobile(BandOfClowns boc) {

    super();

    _clowns = boc;

    }

    public void move() {_clowns.pileIntoCar();

    super.move();

    _clowns.pileOutOfCar();

    }

    } // end of class CrazyCS15Mobile

  • 8/8/2019 06 Interfaces[1]

    4/27

    September 21, 2006Interfaces 4 of 27

    Remember that overriding allows us to

    replace superclass definition of method

    Partial overriding is overriding superclass

    method in part:

    - reusing functionality from superclass method ratherthan completely replacing it

    - calling superclass method of the same name usingsuper, plus providing additional code

    public void move() {

    // add some extra functionality_clowns.pileIntoCar();

    /*** We want to move like the superclass, so* we call superclass move() method. No* need to repeat code that is already* written in CS15Mobiles move() method!*/super.move();

    // add some more functionality_clowns.pileOutOfCar();} // end of move()

    Send in the Clowns: Partial Overriding (2 of 3)

    note: can call thisfrom anywhere,even repeatedly...

  • 8/8/2019 06 Interfaces[1]

    5/27

    September 21, 2006Interfaces 5 of 27

    Partial Overriding (3 of 3)

    super.move() can be called more than once

    super.move() can even be called in another

    method

    This illustrates how subclass can use

    superclass method to manipulate superclassprivate property which remains hidden from

    subclass

    What would happen here if we called

    this.move() instead ofsuper.move()?Exception in thread "main"

    java.lang.StackOverflowError

  • 8/8/2019 06 Interfaces[1]

    6/27

  • 8/8/2019 06 Interfaces[1]

    7/27

    September 21, 2006Interfaces 7 of 27

    Pseudo-Inheritance Diagram

    The state of a subclass consists of- all the instance variables explicitly declared

    - all of the instance variables pseudo-inherited

    Therefore your initialization has two pieces- The single line where you instantiate your pseudo-

    inherited variables by having the superclass initializethem, using super().

    - the piece where you instantiate your instance variables

    Subclass

    Method

    Method

    Method

    Method Method

    Mutator

    Method

    Method

    Accessor

    Method

    from Superclassfrom Subclass

    Instance Vars

  • 8/8/2019 06 Interfaces[1]

    8/27

    September 21, 2006Interfaces 8 of 27

    Visibility Modifiers

    Visibility Modifiers specify what classes see or

    know about- methods or instance variables of other classes

    They are thepublic,private, andprotectedkeywords you have used so far

    Effects of visibility:- cannot reference or instantiate classes which are

    invisible to you.

    - cannot call methods that are invisible to you

    - cannot directly access instance variables which areinvisible to you

    but accessors and mutators permit safe access

  • 8/8/2019 06 Interfaces[1]

    9/27

    September 21, 2006Interfaces 9 of 27

    private

    Generally do not declare classesprivate

    private methods:- invisible to all other classes

    - neverinherited by subclasses

    - called implementation orhelpermethods because

    they are written for convenience and code reuse, butare never used outside of the class

    private instance variables:- same visibility asprivate methods

    - generally, make every instance variableprivate- if other classes need to know about a class instance

    variables, use accessor and mutator methods

    -private instance variables are pseudo-inherited

    the subclass inherits them but can not access them

    directly

  • 8/8/2019 06 Interfaces[1]

    10/27

    September 21, 2006Interfaces 10 of 27

    protected

    protectedclasses:- classes cannot be declared protected

    protectedmethods:- visible to other classes in same package

    - invisible to classes in different packages

    - inherited by subclasses in this or any other package

    protectedinstance variables:- same visibility as protected methods

    - since protected instance variables are visible to all classes

    in same package, generally avoid them

    - exception is when you want subclasses (in all packages) to

    inherit instance variables

    If you have a class and you want to have certain

    instance variables be available to subclasses, useprotected, otherwise useprivate

    Hmm... I

    remember learning this

    in the Inheritance

    lecture!

  • 8/8/2019 06 Interfaces[1]

    11/27

    September 21, 2006Interfaces 11 of 27

    public (1 of 2)

    Thepublic modifier means things are visible

    to all other classes

    public classes:- visible to other classes in same package and visible to

    classes in other packages

    - good for reusing existing code- public classes generally go in their own file and filename

    must be the same aspublic class name.

    - generally, make every classpublic

    exception is implementation or helper classes which you

    would never want other packages to know about and

    would never want to reuse - these are internal. We willsee some of this later.

    public methods:- visible to all classes that can see the class

    - inherited by subclasses

    - generally make every methodpublic exception is implementation or helper methods which

    you are writing for convenience and code reuse - these

    are internal

  • 8/8/2019 06 Interfaces[1]

    12/27

    September 21, 2006Interfaces 12 of 27

    public (2 of 2)

    public instance variables:- Bad, BAD, BAD, BAD, BAD, BAD!!!!

    - did we mention that these are BAD?- NEVER make instance variablespublic

    - exposes instances state to other classes and permits direct

    modification of state

    - completely breaks idea of encapsulation

    - if you need to provide access to private instance variables,

    use accessors and mutators- oh, and by the way,public instance variables are

    considered BAD form, a sign of poor upbringing, poor taste,

    poor lifestyle, and just plain cluelessness

    Usingpublic instance variables is as smart as stickinga key in an electrical outlet:

  • 8/8/2019 06 Interfaces[1]

    13/27

    September 21, 2006Interfaces 13 of 27

    Lost References / Garbage Collection

    What happens when a variable goes out of

    scope?- you can no longer use the variables name to access the

    instance it refers to

    - you lose a reference to that instance

    How else can you lose a reference to an

    instance?- assign variable to null (no useful value)- assign variable to some other instance

    What happens when nothing references an

    instance?- the instance is garbage collected it is removed frommemory by the Java Virtual Machine

    So make sure you dont lose all references to an

    instance -- else you wont be able to access it

    anymore and the instance will disappear!

  • 8/8/2019 06 Interfaces[1]

    14/27

    September 21, 2006Interfaces 14 of 27

    Garbage Collection Example

    package PlanetOfTheApes;

    public class HumanCage {

    private Ape _guard;

    public HumanCage() {

    }

    public void setEvilGuard() {_guard = new

    Ape(java.awt.Color.orange);}

    public void setNiceGuard() {_guard = new

    Ape(java.awt.Color.black);

    }

    }

    public class TestApp() {

    private HumanCage _humanCage;public TestApp() {

    _humanCage = new HumanCage();_humanCage.setEvilGuard();_humanCage.setNiceGuard();

    }}

  • 8/8/2019 06 Interfaces[1]

    15/27

    September 21, 2006Interfaces 15 of 27

    Garbage Collection

    When the methodsetEvilGuard()iscalled

    _guard

    When the methodsetNiceGuard() iscalled

    _guard

    The old instance of

    Ape gets erased(goodbye Dr.Zaius!)

    - works the same for local variables that

    go out of scope!

  • 8/8/2019 06 Interfaces[1]

    16/27

    September 21, 2006Interfaces 16 of 27

    BouncingBalls and CS15Mobiles

    ABouncingBall and a CS15Mobile are very

    different

    But there are some things that both can do

    BouncingBalls and CS15Mobiles can havea mutable color- their color can be accessed and changed

    (by using accessors and mutators like we saw before)

    But they certainly dont inherit from a commonsuperclass

    How do we model similarities in objects that are

    inherently different?

  • 8/8/2019 06 Interfaces[1]

    17/27

    September 21, 2006Interfaces 17 of 27

    Interfaces

    Much like two objects are related if they inherit

    from the same superclass, objects can be related ifthey implement the same interface

    Superclasses factor out responsibilities among

    similar classes that model an is-a hierarchy

    Interfaces are mainly used to factor out

    responsibilities among very different classes

    whose only commonality are specific shared

    capabilities- models the acts-as relationship

    For example, bothDemos.Bounce.BouncingBall andCS15Mobile might implement thewheels.Colorable interface

    - they both act as Colorables objects that have the capability to have a color

  • 8/8/2019 06 Interfaces[1]

    18/27

    September 21, 2006Interfaces 18 of 27

    More Interfaces

    Interfaces only declare capabilities that object

    must have there are no definitions

    - no code! (except declarations)

    Interfaces are similar to abstract classes in that

    all methods are abstract, except that they have:- no constructor

    - usually no instance variables

    - list of responsibilities (public methods) and

    nothing else

    Interfaces prescribe very generic roles- professor, Head TAs and TAs all teach as part of

    their responsibility but they come from different class hierarchi

    and teach in different ways

    - another role they share is Brown citizen

    Interface names are often adjectives, ending in

    -able or-ive.- examples: Colorable, Rotatable

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

    What might a Colorable interface look like?

  • 8/8/2019 06 Interfaces[1]

    19/27

    September 21, 2006Interfaces 19 of 27

    Colorable Interface Syntax

    package wheels; // Short for training wheels

    /*** This interface models something

    * with a changeable color. It

    * specifies that all classes

    * implementing it must allow their

    * color to be 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!

  • 8/8/2019 06 Interfaces[1]

    20/27

    September 21, 2006Interfaces 20 of 27

    Colorable Interface Syntax Explained

    public interface Colorable {- declaration for an interface- same as for class, except interface instead of

    class

    public void setColor( java.awt.Color c );- specifies that anything that acts as a 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 the simplicity of methods- Colorable interface only specifies accessor and

    mutator methods forColor- methods can only beabstract, so that keyword

    can be left off- methods can only bepublic, 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 interface

    Note that there is no executable code and henceno code sharing with interfaces - it is purely a contractualmechanism that puts allimplementation responsibilities on theimplementors

  • 8/8/2019 06 Interfaces[1]

    21/27

    September 21, 2006Interfaces 21 of 27

    Implementing Interfaces

    Classes can extend only one other class

    Classes can implement any numberof interfaces

    Classes 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 that is even more general and flexible

    than others:- classes and instances

    - methods and parameters

    - superclasses and subclasses- interfaces and implementations

  • 8/8/2019 06 Interfaces[1]

    22/27

    September 21, 2006Interfaces 22 of 27

    Implementing Interfaces: Syntax

    package Demos.Car;

    /**

    * This class models a CS15Mobile

    * that implements the Colorable

    * interface.

    */

    public class CS15Mobile extends Car implements

    Colorable {

    private java.awt.Color _color;

    // other instance variables

    // constructor

    public void setColor( java.awt.Color c ) {

    _color = c;

    }

    public java.awt.Color getColor() {

    return _color;

    }

    // other methods

    }

  • 8/8/2019 06 Interfaces[1]

    23/27

    September 21, 2006Interfaces 23 of 27

    Interface Syntax Explained

    public class CS15Mobile extends Car implementsColorable {

    - CS15Mobile extends Car but also implementsColorable

    - implementing an interface is as simple as using the wordimplements

    - to implement multiple interfaces, just separate them by a

    comma

    e.g., implements Colorable, Locatable,Mover

    CS15Mobile defines the Colorable interface

    methods by making them simple accessors and

    mutators- could also do something more complicated- Java 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?- you get a compiler error the same thing that happens if

    you dont define an abstract method of a superclass- class must be declared abstract

  • 8/8/2019 06 Interfaces[1]

    24/27

    September 21, 2006Interfaces 24 of 27

    Interfaces, Inheritance, Extensibility

    Like classes, interfaces can extend other interfaces

    Unlike classes, interfaces can extend any numberof other interfaces- this is because interfaces merely declare policy they

    never specify any implementation- just put a comma between interface names afterextends

    Extending multiple interfaces is useful for objects

    that have some things in common but otherwise

    behave very differently- example: GUI components (e.g., PushButton,TextBox,Menu)

    - they all behave and react very differently- but they all have the capability to be located on the screen

    and sized- so a Component interface is created that extends bothLocatable and Sizeable

    Remember: objects inherit all capabilities from their

    superclasses, so an object inherits all interfaces from its

    superclass- therefore if a superclass implements an interface, the

    subclass implements it too!

    I l ti M lti l I t f

  • 8/8/2019 06 Interfaces[1]

    25/27

    September 21, 2006Interfaces 25 of 27

    Implementing Multiple Interfaces

    Implementing multiple interfaces is easy- Just implement the union of all their methods!

    public interface Mover {

    public void move();

    }

    public interface Shaker {

    public void shake();}

    public class Politician implementsMover,Shaker {

    //constructor

    public void move() {

    //code to move

    }

    public void shake() {

    //code to shake

    }

    }

    C fli ti M th d i I t f

  • 8/8/2019 06 Interfaces[1]

    26/27

    September 21, 2006Interfaces 26 of 27

    Conflicting Methods in Interfaces

    What if we have a method declared in two different

    interfaces with the same exact signature?- this should happen only if you really mean them to specify the

    same behavior

    - thus we only need to define the method once

    What if we have methods with the same name but with

    different signatures (e.g., parameter lists) declared in

    different interfaces?- this should happen if different behaviors were meant, and thecoincidence of the names being identical was either accidental

    or meant to suggest similarity in behaviors

    - either way, we must define each method appropriately

    What if these methods have the same name and the same

    signature but I want them to mean different things?- bummer!

    - you should rename one of those methods to avoid the

    semantic conflict

    What if we have methods with the same signature, but

    different return types? (Recall: return types are not part ofthe signature.)- ERROR!

    - have to either not implement one of the interfaces, or change

    the signatures of the methods in the interfaces.

    Announcements

  • 8/8/2019 06 Interfaces[1]

    27/27

    September 21, 2006Interfaces 27 of 27

    Announcements

    Textbook Reading Assignment- 5.1-5.3

    References is OUT- Due next Thursday, Sept 28 at 5:00PM

    LiteBrite is due TODAY (11:59PM)!!!

    - Late date is Saturday at 9:59

    If you wanted a tutor, but didnt contact one yet,

    please come see a HTA after class!

    WiCS (Women in Computer Science)- Google dinner tonight at 7:00, if you are interested come

    talk to Tatyana!

    Careers in CS!

    - Google info session today at 4:00PM on the 4th Floor ofthe CIT (Lubrano Room)

    - Pixar info session today at 7:30 in Pembroke Hall