28
© 2006 Pearson Education Interfaces 1 of 28 INTERFACES • Declaring Interfaces • Implementing Interfaces • Using Interfaces Polymorphically • Visibility Modifiers

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

Embed Size (px)

Citation preview

Page 1: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 1 of 28

INTERFACES

• Declaring Interfaces

• Implementing Interfaces

• Using Interfaces Polymorphically

• Visibility Modifiers

Page 2: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 2 of 28

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” color their color can be queried for and changed (by using accessors and mutators like we saw before)

• But they certainly don’t inherit from a common superclass

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

Page 3: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 3 of 28

Interfaces

• Much 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 capabilities models the “acts-as” relationship

• For example, both BouncingBall and CSMobile might implement the wheels.Colorable interface they both “act as” Colorables

• objects that have the capability to have a color

Page 4: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 4 of 28

More Interfaces

• Interfaces only declare capabilities that object must have — there are no definitions no code! (except declarations)

• Similar to abstract classes with all methods abstract, except no constructor usually no instance variables list of responsibilities (public methods) and nothing

else

• Interfaces prescribe very generic roles professors, 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 -er examples: Container, Mover, Teacher

• What might a Colorable interface look like?

Page 5: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 5 of 28

Colorable Interface Syntax

package 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!

Page 6: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 6 of 28

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 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 methods­ Colorable interface only specifies accessor and mutator

for Color methods can only be abstract, so that keyword can be

left off methods can only be public, but we leave that keyword

in for the sake of clarity

• That’s it! interfaces are really simple! in fact, this is almost verbatim the code in the actual wheels.Colorable interface

wheels 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

Page 7: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 7 of 28

Implementing Interfaces

• Classes 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 others classes and instances methods with parameters superclasses and subclasses interfaces and implementations

Page 8: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 8 of 28

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

}

Page 9: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 9 of 28

Interface Syntax Explained

public class CSMobile extends Car implements Colorable {

­ CSMobile extends Car but also implements Colorable

implementing an interface is as simple as using the word implements

to implement multiple interfaces, just separate them by a comma• e.g., implements Colorable, Locatable, Mover

•CSMobile defines Car‘s interface methods by making them simple accessors and mutators could also do something more complicated Java doesn’t care how you define the methods of an

interface, just that you do define them

• What happens if you don’t define a method of an interface you implement? same thing that happens if you don’t define an

abstract method of a superclass class must be declared abstract

Page 10: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 10 of 28

Using Interfaces Polymorphically

• Interfaces can be used as types of variables and parameters, just like classes e.g., CSMobile can be referenced polymorphically as CSMobile, Car, and Colorable

you can even declare an instance or local variable as an interface• e.g., Colorable myColorable;

• Methods which accept parameters of interface type don’t care what actual class of object will be do care that object responds to messages declared in

interface don’t 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

Page 11: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 11 of 28

More Polymorphism in Interfaces

• Many 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?

Page 12: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 12 of 28

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

Page 13: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 13 of 28

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);

}

}

Page 14: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 14 of 28

PaintShop/PaintProgram Syntax

public void randomPaintJob(wheels.Colorable

colorable)­ randomPaintJob has parameter representing the wheels.Colorable it is working on

this 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.Colorable

because colorable implements the Colorable interface, it must have a setColor method

don’t 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 parameter

when randomPaintJob is called, it will set the color of the CSMobile to a random color

the same thing applies for _rect which is a wheels.users.Rectangle and acts as a wheels.Colorable

• Note: Cars and Shapes may implement setColor() in very different ways!

Page 15: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 15 of 28

Interfaces, Inheritance, Extensibility

• Like classes, interfaces can extend other interfaces

• Unlike classes, interfaces can extend any number of other interfaces this is because interfaces merely declare policy —

they never specify any implementation just 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 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

both Locatable 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!

Page 16: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 16 of 28

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 implements Mover, Shaker {

//constructor

public void move() {

//code to move

}

public void shake() {

//code to shake

}

}

Page 17: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 17 of 28

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 the coincidence 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 of the signature.) ERROR! have to either not implement one of the interfaces, or

change the signatures of the methods in the interfaces.

Page 18: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 18 of 28

Factors out common properties and capabilities of similar objects

Interface Class

Differences Between Interfaces and Classes

Models a role; defines a set of responsibilities

Models an object with properties and capabilities

Factors out common capabilities of dissimilar objects

Declares, but does not define, methods

Declares methods and may define some or all of them

A class can implement multiple interfaces

A class can extend only one superclass

Page 19: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 19 of 28

Polymorphism Review• Key points about Polymorphism:

subclass inherits methods from superclass• so, subclass can respond to at least the same messages

as superclass an instance of a subclass can be referred to as if it were an

instance of its superclass• though only the methods of the superclass may be called• In this situation the superclass is known as the “declared

type” and subclass as the “actual type” instance of subclass will respond to implementation defined in

subclass

• All of these points apply to interfaces• Essentially, replace “subclass” with “implementer” and

“superclass” with “interface”

• Assume we have the following class definitions: public class Car implements Mover { } public class CSMobile extends Car { }

• Are the following assignments legal? If not, why not?

CSMobile mobile = new CSMobile(); Car myCar = new CSMobile(); CSMobile anotherMobile = myCar; Mover myMover = myCar; myMover = new CSMobile(); CSMobile yetAnotherMobile = myMover;

Page 20: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 20 of 28

Polymorphism Review (cont.)

• Remember ­ CSMobile “is a” Car­ Car “acts as” a Mover

• But:­ Car “is a” CSMobile? Does CSMobile “act as” a Mover? Does a Mover “act as” a Car?

• Answers to previous page:­ CSMobile mobile = new CSMobile();

• legal; standard instantiation and assignment­ Car myCar = new CSMobile();

• legal; CSMobile “is a” Car­ CSMobile anotherMobile = myCar;

• illegal; a generic Car is not necessarily a CSMobile­ Mover myMover = myCar;

• legal; Car “acts as” a Mover­ myMover = new CSMobile();

• legal; CSMobile “is a” Car which “acts as” a Mover­ CSMobile yetAnotherMobile = myMover;

• illegal; an object which “acts as” a Mover is not necessarily a CSMobile

Page 21: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 21 of 28

Visibility Modifiers

• Visibility Modifiers specify what classes “see” or “know about” other classes or interfaces methods or instance variables of other classes or

interfaces

• They are the public, private, and protected you have used so far

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

“invisible” to you. cannot reference or implement interfaces which are

“invisible” to you cannot call methods that are invisible to you cannot directly access instance variables which are

invisible to you• but accessors and mutators provided to you permit

safe access

Page 22: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 22 of 28

public (1 of 2)

• The public modifier means things are visible to all other classes

•public classes and interfaces: visible to other classes in same package and visible

to classes in other packages good for reusing existing code public classes generally go in own file and filename

must be the same as public class name. generally, make every class public

• 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

•public methods: visible to all classes to which the class they are a

part of is visible inherited by subclasses generally, make every method public

• exception is implementation or helper methods which you are writing for convenience and code reuse - these are internal

Page 23: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 23 of 28

public (2 of 2)

•public instance variables: Bad, BAD, BAD, BAD, BAD, BAD!!!! did we mention that these are BAD? NEVER make instance variables public exposes instance’s 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

with all that said, you’ll see an exception to this rule in the next lecture

Avast ye mateys!Death to scurvy sea dogs who use public instance variables!

Page 24: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 24 of 28

protected

•protected classes and interfaces: classes and interfaces cannot be declared protected

•protected methods: visible to other classes in same package invisible to classes in different packages inherited by subclasses in this or any other package

•protected instance 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, use protected, otherwise use private

Page 25: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 25 of 28

private

• Generally do not declare classes or interfaces private

•private methods: invisible to all other classes never inherited by subclasses called implementation or helper methods because

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

•private instance variables: same visibility as private methods generally, make every instance variable private if other classes need to know about a class’ instance

variables, use accessor and mutator methods exception is instance variables which only

subclasses must access/inherit; in that case, make instance variable protected

Page 26: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 26 of 28

Package Friendly

• Another accessibility category: Package Friendly

• Classes, interfaces, methods, or instance variables which are declared without visibility modifiers are package friendly

Page 27: © 2006 Pearson EducationInterfaces1 of 28 INTERFACES Declaring Interfaces Implementing Interfaces Using Interfaces Polymorphically Visibility Modifiers

© 2006 Pearson EducationInterfaces 27 of 28

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

© 2006 Pearson EducationInterfaces 28 of 28