George BlankUniversity Lecturer
04/18/232
Designing to a Java InterfaceThinking abstractly at a high level
A Key Java SkillSpyridon Baroulakis
George Blank
04/18/233
Introduction• When we create a class that matches a specification,
we say that the class implements the specification.• In this chapter, we will visit four Java constructions for
designing classes and connecting them to their collaborating classes.
• We will see how interfaces tie in with the rest of the constructs and through polymorphism, multiple inheritance, and abstraction enhance the functionality of Java.
04/18/234
Why we need specifications• A program is assembled from a collection of classes
that must work together. What does that mean?• Say you receive a portable CD player as a gift. When
you operate the player nothing happens. It requires batteries. Fortunately, a label in the back instructs that you need 2 AA batteries. Once you insert the proper count and type of batteries, the completed “assembly” now operates seamlessly. You do not need to know how power makes it work, just that you need batteries.
Objectives:
1. Most Important: Learn to use interfaces in Java to think about code before you develop it. (Philosophy)
2. Learn how to use interfaces in Java (Mechanics)
3. Learn the differences between interfaces and abstract classes
04/18/236
Why design to an interface?
• “Designing to a Java Interface” comes from the slogan:
• “Program to the interface, not the implementation!”• When you write a class that depends on another,
collaborator class, you should rely on the collaborator’s interface – its specification – and not its coding (its implementation).This way you design classes separately yet the assembled collection works.
04/18/237
Why design to an interface?• A higher level of abstraction allows us to utilize
methods and classes with a higher degree of commonality.
• Structures and approaches can be shared in a wider variety of implementations.
• You can reuse frameworks of the past and improve on functionality without having to make any changes to already existing work. You simply improve on the next iteration.
04/18/238
What are the four constructs• Java interfaces, which define specifications that a coded
class must implement.• Java inheritance (extends), which defines a new class
by adding methods onto an already written class.• Java abstract classes, which are “incomplete” classes,
part specification and part implementation.• Java polymorphism, which allows a common set of
methods to be implemented between several families of classes.
04/18/239
Java interfaces• Interfaces allow functionality to be shared between
objects that agree to a contract on how the software should interact as a unit without needing knowledge of how the objects accomplish their task.
• On the CD player example, you have a contract with the manufacturer that once you press play, you will hear music. You do not know the specifics of how it is accomplished but you know what will happen. You have both agreed on an interface.
04/18/2310
Java interfaces• An interface is a reference type that can contain only
nested types, method signatures and constants.• Method bodies are not defined.• Can not be instantiated.• Can be implemented by other classes.• Can be extended by other interfaces.• All methods in an interface are automatically public
abstract even if not explicitly stated as such.
04/18/2311
Java interfacespublic interface OperateCar {
// declarations of variables
int signalTurn(direction,speed); }
• Note that the method signature has no braces and is terminated by a semicolon.
• To use an interface you write a class that implements the interface.
04/18/2312
Java interfacespublic class BMWCar implements OperateCar {
int signalTurn(direction,speed){
// proprietary code to signal you are turning }
• A Toyota manufacturer may have different positioning of the signals on the car, different signal colors, different light intensity, but he is guaranteeing that when you use signalTurn you will get the same behavior as the BMW car.
04/18/2313
Interfaces and Inheritance• Java does not permit multiple inheritance like C++.• Some people would say that is a weakness of Java, but
there is an alternative view that says Java’s interfaces give the advantages of multiple inheritance while avoiding some of the problems.
• One of the key problems with multiple inheritance is known as the diamond problem. It occurs when a class inherits from two classes with a common ancestor.
04/18/2314
The Diamond Problem
Gas EngineIgnition: spark plugs
Engine
Ignition
Diesel Engine
Ignition: glow plugs
Multifuel Engine
Ignition: ??????
When a class inherits from two classes that implement common methods in different ways, what does it inherit?
04/18/2315
The Diamond Problemabstract class Engine {abstract void
Ignition(method)};
class gasEngine extends Engine { void Ignition(spark_plugs); }
class dieselEngine extends Engine { void Ignition(glow_plugs); }
class MultiFuelEngine extends gasEngine,dieselEngine { Ignition()???}
• Runtime cannot determine whether it should invoke Ignition() from gas or diesel engines.
04/18/2316
Java’s Solution• Java solves the diamond problem by not
allowing multiple inheritance from ancestors that have any implementation details.
• Thus, in Java, classes can only multiply inherit from interfaces and abstract classes that have no implementation details.
04/18/2317
Interfaces and Inheritance• One interface can inherit another by use of the keyword extends. When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the interface inheritance chain.
• Why would we need to have one interface inherit from another instead of modifying the original one? Because all of the implementations we have written in the past would now break. Not all methods would be implemented and we would have to revisit past work.
04/18/2318
Interfaces and Inheritance• To solve this problem without breaking our previous
work, we create a new interface that extends the original one to add new functionality to our design.
interface AnyKid { void mayCry();}
interface MyKid extends AnyKid { void isSmart();}
• How do we use the new features that were added in a new class implementation?
04/18/2319
Interfaces and Inheritanceclass MySon implements MyKid {
public void mayCry(){System.out.println(“Its ok”);}
public void isSmart() {System.out.println(“But he is certainly VERY smart”); } }
• A class can also implement more than one pertinent interface at the same time but can not inherit from more than one other class.
04/18/2320
Inheriting from Two Interfaces
• For a class to inherit from two interfaces, it must provide implementation for all methods declared in each interface.
public class StudentEmployee implements Student, Employee {
… implement all methods here.• If there is a conflicting method defined in both
interfaces the compiler will let us know !
04/18/2321
Abstract methods
• You can declare an object without defining it:Employee john;
• Similarly you can declare a method without defining it:
public abstract void draw(Graphics g);
Notice that the body of the method is missing !• A method that has been declared but not
defined is an abstract method.
04/18/2322
Abstract Classes
• Any class containing an abstract method is an abstract class.
• You must declare the class with the keyword abstract.
abstract class MyClass { … };
• An abstract class is incomplete. Its method bodies have “missing” implementations.
• You can not instantiate (create a new instance of) an abstract class.
04/18/2323
Abstract Classes
• You can extend (subclass) an abstract class.– If the subclass defines all the inherited abstract
methods, it is “concrete” and can be instantiated.– If the subclass does not define all of the inherited
abstract methods, it too needs to be defined abstract.
• You can define a class to be abstract even if it does not contain any abstract methods.– This prevents the class from being instantiated.
• You can have one or more methods provide full implementation if they are to be used frequently in the same manner.
04/18/2324
Why have Abstract Classes?
• Suppose you wanted to create a class Shape with subclasses Oval, Rectangle, Triangle .
• You do not want to allow the creation of a Shape– Only particular shapes make sense, not generic
ones.– If Shape is abstract, you can’t create a new Shape .– You can create a new Oval, new Rectangle .
• Abstract classes are used in providing a general category containing specific, “concrete” classes.
04/18/2325
Abstract Classes
public abstract class Shape {
//can define constants
public static final double TWO_PI=2*Math.PI;
//can declare abstract methods
public abstract double computeArea();
public abstract void draw();
//can implement concrete methods
public String returnExample()
{return “euclidean”;} }
04/18/2326
Abstract Classes vs. Interfaces
• An interface is a list of unimplemented, and therefore abstract, methods. So how does it differ from an abstract class?
• An interface can not have any methods implemented, whereas an abstract class can.
• A class can implement many interfaces but can only inherit from one superclass.
• An interface is not part of the class hierarchy. Unrelated classes can implement the same interface.
04/18/2327
Abstract Classes vs. Interfaces
• Use an abstract class when you want a roadmap for a collection of subclasses.
• Subclass when you want to extend a class and add some functionality, whether or not the parent class is abstract.
• Subclass when you must ! (e.g. Applets)• Define an interface when there is no common
parent class with the desired functionality, and when you want only certain unrelated classes to have that functionality.
04/18/2328
Abstract Classes vs. Interfaces
• Use interfaces as “markers” to indicate something about a class (e.g. Cloneable – be able to make a copy).
• A common design pattern is to use both an interface and an abstract class depending on the needs of the project.
• All classes share a single root, the Object class, but there is no single root for interfaces.
04/18/2329
Polymorphism• Polymorphism, reusability and extendibility
tend to be the most common reasons that Java programmers use interfaces. They are closely related because all depend on the flexibility of inheriting from an interface.
• Designing to an interface often means designing at a high level of abstraction so that methods and classes with a high degree of commonality can share structure and approaches.
04/18/2330
Sample Problem• Let us say that you are bored watching
the fish tank screen saver on your computer and want a view that shows animals walking, birds flying, and fish swimming on your screen at the same time.
• Here is an approach to designing with interfaces for polymorphism.
04/18/2331
Requirements• Here we are assuming that walk, swim and
fly are all successive animations, but follow different rules.
• Walking can only take place on land and must stay in contact with the ground.
• Flying can only take place in the air.• Swimming can only take place in the water.
04/18/2332
Interface Exampleinterface Mover {
void move();
}
abstract class Animal implements Mover {
abstract public void move();
}
04/18/2333
Using the abstract classclass Mammal extends Animal {
public void move(){…walk…
}}class Bird extends Animal {
public void move(){…fly…
}}class Fish extends Animal {
public void move(){…swim…
}}
04/18/2334
Further investigation• The preceding example is just getting started.
An animation usually requires several images (different wing positions for a bird, etc.). There may be different kinds of birds. Each animal will have a current image and a current position on the screen. Each move will have a direction, velocity, and length of movement. How would you modify the interface to accommodate these specifications?
04/18/2335
References• http://
www.cs.sjsu.edu/~kim/46b/contents/handouts/interfaces.doc
• http://www.apl.jhu.edu/Notes/LMBrown/resource/Abstract-Classes.pdf
• http://www.cs.virginia.edu/~horton/cs494/slides/java-interfaces-collections.ppt
• http://java.sun.com/docs/books/tutorial/java/IandI/createinterface.html
04/18/2336
References• http://
gee.cs.oswego.edu/dl/cpj/ifc.html#secAbs• http://www.cs.umd.edu/~clin/MoreJava/
Objects/absclass.html• http://www.uweb.ucsb.edu/~cdecuir/
Abstraction%20and%20Interfaces.html• http://www.csie.ntnu.edu.tw/~ghhwang/
course_slices/PL/Java_interface_more.ppt• http://cs.nyu.edu/courses/spring07/V22.0101-
002/10slide.ppt
04/18/2337
References• http://people.cis.ksu.edu/~schmidt/PPJv12pdf/
ch9V12.pdf• http://www.cis.upenn.edu/~matuszek/cit591-
2003/Lectures/28-abstract-classes.ppt• http://people.clarkson.edu/~jets/cs242/fa07/
slides/05.classDesign.ppt