37
George Blank University Lecturer

George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

Embed Size (px)

Citation preview

Page 1: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

George BlankUniversity Lecturer

Page 2: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

04/18/232

Designing to a Java InterfaceThinking abstractly at a high level

A Key Java SkillSpyridon Baroulakis

George Blank

Page 3: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 4: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 5: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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

Page 6: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 7: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 8: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 9: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 10: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 11: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 12: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 13: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 14: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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?

Page 15: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 16: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 17: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 18: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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?

Page 19: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 20: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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 !

Page 21: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 22: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 23: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 24: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 25: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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

Page 26: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 27: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 28: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 29: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 30: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 31: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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.

Page 32: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

04/18/2332

Interface Exampleinterface Mover {

void move();

}

abstract class Animal implements Mover {

abstract public void move();

}

Page 33: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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…

}}

Page 34: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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?

Page 36: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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

Page 37: George Blank University Lecturer. 5/20/2015 2 Designing to a Java Interface Thinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George

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