Вы находитесь на странице: 1из 37

George Blank University Lecturer

Designing to a Java Interface


Thinking abstractly at a high level
A Key Java Skill Spyridon Baroulakis George Blank

6/23/2011

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.

6/23/2011

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.

6/23/2011

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

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 collaborators interface its specification and not its coding (its implementation).This way you design classes separately yet the assembled collection works.

6/23/2011

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.

6/23/2011

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.

6/23/2011

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.

6/23/2011

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.

10

6/23/2011

public interface OperateCar { // declarations of variables int signalTurn(direction,speed); }

Java interfaces

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.

11

6/23/2011

public class BMWCar implements OperateCar { int signalTurn(direction,speed){ // proprietary code to signal you are turning }

Java interfaces

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.

12

6/23/2011

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 Javas 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.

13

6/23/2011

The Diamond Problem


Engine Ignition Gas Engine Ignition: spark plugs 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? 14
6/23/2011

The Diamond Problem


abstract 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.

15

6/23/2011

Javas 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.

16

6/23/2011

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.

17

6/23/2011

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?

18

6/23/2011

class MySon implements MyKid { public void mayCry(){System.out.println(Its ok);} public void isSmart() {System.out.println(But he is certainly VERY smart); } }

Interfaces and Inheritance

A class can also implement more than one pertinent interface at the same time but can not inherit from more than one other class.

19

6/23/2011

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 !

20

6/23/2011

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.

21

6/23/2011

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.

22

6/23/2011

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. 23
6/23/2011

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 cant 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.

24

6/23/2011

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

25

6/23/2011

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.

26

6/23/2011

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.

27

6/23/2011

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.

28

6/23/2011

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.

29

6/23/2011

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.

30

6/23/2011

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.

31

6/23/2011

Interface Example
interface Mover { void move(); } abstract class Animal implements Mover { abstract public void move(); }

32

6/23/2011

Using the abstract class


class Mammal extends Animal { public void move(){ walk } } class Bird extends Animal { public void move(){ fly } } class Fish extends Animal { public void move(){ swim } }

33

6/23/2011

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?

34

6/23/2011

References
http://www.cs.sjsu.edu/~kim/46b/contents/handouts/i nterfaces.doc http://www.apl.jhu.edu/Notes/LMBrown/resource/Abst ract-Classes.pdf http://www.cs.virginia.edu/~horton/cs494/slides/javainterfaces-collections.ppt http://java.sun.com/docs/books/tutorial/java/IandI/cre ateinterface.html

35

6/23/2011

References
http://gee.cs.oswego.edu/dl/cpj/ifc.html#secAbs http://www.cs.umd.edu/~clin/MoreJava/Objects/abscl ass.html http://www.uweb.ucsb.edu/~cdecuir/Abstraction%20a nd%20Interfaces.html http://www.csie.ntnu.edu.tw/~ghhwang/course_slices/ PL/Java_interface_more.ppt http://cs.nyu.edu/courses/spring07/V22.0101002/10slide.ppt

36

6/23/2011

References
http://people.cis.ksu.edu/~schmidt/PPJv12pdf/ch9V1 2.pdf http://www.cis.upenn.edu/~matuszek/cit5912003/Lectures/28-abstract-classes.ppt http://people.clarkson.edu/~jets/cs242/fa07/slides/05. classDesign.ppt

37

6/23/2011