62
Object-Oriented Design and Programming (Java)

Object-Oriented Design and Programming (Java)

Embed Size (px)

DESCRIPTION

Object-Oriented Design and Programming (Java). Topics Covered Today. 2.3 Advanced Class Design 2.3.1 Abstract Classes ( 抽象类 ) 2.3.2 Polymorphism ( 多态 ) 2.3.3 Interfaces( 接口 ). Abstract Method. Definition: Methods that do not have implementation (body) - PowerPoint PPT Presentation

Citation preview

Page 1: Object-Oriented Design and Programming (Java)

Object-Oriented Design and Programming (Java)

Page 2: Object-Oriented Design and Programming (Java)

2

Topics Covered Today

• 2.3 Advanced Class Design– 2.3.1 Abstract Classes (抽象类 )– 2.3.2 Polymorphism (多态 )– 2.3.3 Interfaces(接口 )

Page 3: Object-Oriented Design and Programming (Java)

3

Abstract Method

• Definition:– Methods that do not have implementation (body)

• To create an abstract method, just write the method declaration without the body and use the abstract keyword– No { }

• For example, // Note that there is no body public abstract void eat(int amount); public abstract void sleep(int hours);

Page 4: Object-Oriented Design and Programming (Java)

4

Abstract Class.

• Definition: An abstract class is a class that contains one or more abstract methods– Any class which contains an abstract method must

itself be declared abstract.

• An abstract class is denoted by using the abstract modifier– public abstract class ClassName { . . . }

Page 5: Object-Oriented Design and Programming (Java)

5

Abstract Class..

• An abstract class cannot instantiated– No instance of an abstract class can be created.

// You will get a compile error on the following codeMyAbstractClass a1 = new MyAbstractClass();

• If a subclass of an abstract class does not

implement all abstract methods inherited from its parent, the subclass must also be defined as abstract.

Page 6: Object-Oriented Design and Programming (Java)

6

Example

• Consider a chemical company that transports its products in two kinds of containers: wagons and tanks:

Page 7: Object-Oriented Design and Programming (Java)

7

Class Diagram

+computeVolume() : double

Container

+computeVolume() : double

-width : double

-height : double

-length : double

Wagon

+computeVolume() : double

-radius : double

-length : double

Tank

Page 8: Object-Oriented Design and Programming (Java)

8

Class Container

public abstract class Container {

/**

* Computes the volume of this container.

* @return the volume of this container.

*/

public abstract double computeVolume();

}

Page 9: Object-Oriented Design and Programming (Java)

9

Class Wagonpublic class Wagon extends Container {

private double width;private double height;private double length;

public Wagon(double initialWidth, double initialHeight, double initialLength) {

width = initialWidth; height = initialHeight; length = initialLength;

} public double computeVolume() {

return width * height * length; }

}

Page 10: Object-Oriented Design and Programming (Java)

10

Class Tankpublic class Tank extends Container {

private double radius;

private double length;

public Tank(double initialRadius,

double initialLength) {

radius = initialRadius;

length = initialLength;

}

public double computeVolume() {

return Math.PI * radius * radius * length;

}

}

Page 11: Object-Oriented Design and Programming (Java)

11

Business System

+getName() : String-name : String

Person

+getAge() : int-age : int

Employee

+getCredit() : double-credit : double

Client

Page 12: Object-Oriented Design and Programming (Java)

12

Class Person

public abstract class Person {private String name;

public Person(String initialName) {name = initialName;

}

public String getName() { return name; }}

Class can be defined as abstract but it does not contain any abstract methods.

Page 13: Object-Oriented Design and Programming (Java)

13

Class Employee

public class Employee extends Person {

private int age;

public Employee(String initialName,

int initialAge) {

super(initialName);

age = initialAge;

}

public int getAge() {

return age;

}

}

Page 14: Object-Oriented Design and Programming (Java)

14

Class Client

public class Client extends Person {

private double credit;

public Client(String initialName,

double initialCredit) {

super(initialName);

credit = initialCredit;

}

public double getCredit() {

return credit;

}

}

Page 15: Object-Oriented Design and Programming (Java)

15

Using Person 、 Employee & Client

• No instances of class Person can be created because Person is abstract– Person person = new Person();

• Instances of class Employee and Client can be created because they are concrete classes(实体类 )– Employee employee = new Employee("John", 21);– Client client = new Client("Mary", 6000.0);

X

Page 16: Object-Oriented Design and Programming (Java)

16

When to use Abstract Methods & Abstract Class?

• Abstract methods are usually declared where two or more subclasses are expected to fulfill a similar role in different ways through different implementations

• These subclasses extend the same Abstract class and provide different implementations for the abstract methods

Page 17: Object-Oriented Design and Programming (Java)

17

Abstract Class Summary

• For some applications we might want a generic base class that we will never instantiate.

• Note that if any method is declared abstract, the class must be declared abstract as well or the compiler will give an error message.

• An abstract class can include concrete methods and fields.• In fact, an abstract class does not need to include any

abstract methods.. • Note that an abstract method has no code body, no braces

{}. • All of the abstract methods must be overridden by

methods in the concrete subclasses.

Page 18: Object-Oriented Design and Programming (Java)

18

Topics Covered Today

• 2.3 Advanced Class Design– 2.3.1 Abstract Classes (抽象类 )– 2.3.2 Polymorphism (多态 )– 2.3.3 Interfaces(接口 )

Page 19: Object-Oriented Design and Programming (Java)

19

Upcasting Again

public class CellPhone { CellPhone() { //…} public void ring(Tune t) { t.play(); }}public class Tune { public void play() { System.out.println("Tune.play()"); }}public class ObnoxiousTune extends Tune{ ObnoxiousTune() { // …} // …}

Page 20: Object-Oriented Design and Programming (Java)

20

An ObnoxiousTune “is-a” Tune

Tune

ObnoxiousTune

A “UML” diagram

public class CellPhoneDemo { public static void main(String[] args) { CellPhone noiseMaker = new CellPhone(); ObnoxiousTune ot = new ObnoxiousTune(); noiseMaker.ring(ot); // ot works though Tune called for }}

Page 21: Object-Oriented Design and Programming (Java)

21

Aspects of Upcasting

• Upcasting is a cast• The exact type of the object is lost• What gets printed in the CellPhone example?

– Tune.play() (what were you expecting?)

• Is this “the right thing to do”?– The alternative: write separate play() methods for each

subclass of Tune?

Page 22: Object-Oriented Design and Programming (Java)

22

A little Improvementclass CellPhone { CellPhone() { //…} public void ring(Tune t) { t.play(); }}class Tune { Tune() { //…} public void play() { System.out.println("Tune.play()"); }}class ObnoxiousTune extends Tune{ ObnoxiousTune() { // …} public void play() { System.out.println("ObnoxiousTune.play()"); }}

Page 23: Object-Oriented Design and Programming (Java)

23

What Gets Printed Now?public class CellPhoneDemo { public static void main(String[] args) { CellPhone noiseMaker = new CellPhone(); ObnoxiousTune ot = new ObnoxiousTune(); noiseMaker.ring(ot); // ot works though Tune called for }}

Tune

+play()

ObnoxiousTune

+play()

Page 24: Object-Oriented Design and Programming (Java)

24

Polymorphism

• The second example prints ObnoxiousTune.play()– Since an ObnoxiousTune object was sent to ring(),

the ObnoxiousTune’s play() method is called.

• Definition– Through inheritance, a class can be used as more than

one type; it can be used as its own type, any base types, or any interface type if it implements interfaces. This is called polymorphism.

Page 25: Object-Oriented Design and Programming (Java)

25

Method-Call Binding

• The correct method is attached (“bound”) to the call at runtime.

• The runtime system discovers the type of object sent to ring(), and then selects the appropriate play() method:– if it’s a Tune object, Tune’s play() is called– if it’s an ObnoxiousTune object, ObnoxiousTune’s

play() is called

Page 26: Object-Oriented Design and Programming (Java)

26

Is Java Always Late-Binding?

• Yes, always, except for final methods.

• final methods can’t be overridden, so the compiler knows to bind it.

• The compiler may be able to do some speed optimizations for a final method.

• In C++, binding is always at compile-time, unless the programmer says otherwise.

Page 27: Object-Oriented Design and Programming (Java)

27

Another Polymorphism Example

public static void main(String[] args) { CellPhone noiseMaker = new CellPhone(); Tune t; double d = Math.random(); if (d > 0.5) t = new Tune(); else t = new ObnoxiousTune(); noiseMaker.ring(t);}

Page 28: Object-Oriented Design and Programming (Java)

28

References and Subclasses

• A Tune reference can refer to an ObnoxiousTune object.

• This doesn’t work the other way around: any old Tune may not be an ObnoxiousTune.

• So, an ObnoxiousTune reference cannot refer to a Tune object.

Page 29: Object-Oriented Design and Programming (Java)

29

Let’s Fool the Compiler!

public static void main(String[] args) { CellPhone noiseMaker = new CellPhone(); Tune t1 = new Tune(); Tune t2 = new ObnoxiousTune(); noiseMaker.ring(t1); noiseMaker.ring((Tune)t2);}

Nothing changes… ObnoxiousTune.play() ObnoxiousTune.play() is still printed.is still printed.

Page 30: Object-Oriented Design and Programming (Java)

30

Let’s Fool the Compiler!

public static void main(String[] args) { CellPhone noiseMaker = new CellPhone(); Tune t1 = new Tune(); Tune t2 = new ObnoxiousTune(); noiseMaker.ring(t1); noiseMaker.ring((ObnoxiousTune) t2);}

Nothing changes…

Page 31: Object-Oriented Design and Programming (Java)

31

Let’s Fool the Compiler!

public static void main(String[ ] args) { CellPhone noiseMaker = new CellPhone(); Tune t1 = new Tune(); Tune t2 = new ObnoxiousTune(); noiseMaker.ring((ObnoxiousTune) t1); noiseMaker.ring(t2);}

This compiles, but gets a CastClassExceptionat runtime (even though Tune has a play() method).

“Downcasting” can be dangerous!

Page 32: Object-Oriented Design and Programming (Java)

32

Class Container

+computeVolume() : double

Container

+computeVolume() : double

-width : double

-height : double

-length : double

Wagon

+computeVolume() : double

-radius : double

-length : double

Tank

Page 33: Object-Oriented Design and Programming (Java)

33

Polymorphism

• A reference variable can hold a reference to an object of the declared type or any subtype of the declared type (一个引用变量可以引用它所属类型及它的子类的对象 )– Container container;

– container = new Wagon(1, 1, 3);

– container = new Tank(1, 3);

• When a polymorphic method is called, the Java Virtual Machine (JVM) determines which version of the method to execute by examining the reference variable used in the method call.– double volume = container.computeVolume();

Page 34: Object-Oriented Design and Programming (Java)

34

Exampleimport java.io.*;

public class ContainerDemo {

private static PrintWriter stdOut = new PrintWriter(System.out, true);

public static void main(String[] args) {

Container container;

container = new Wagon(1, 1, 3);

stdOut.println("Volume: " + container.computeVolume());

container = new Tank(1, 3);

stdOut.println("Volume: " + container.computeVolume());

}

}Volume:3.0

Volume:9.4247777

Page 35: Object-Oriented Design and Programming (Java)

35

Method-Call Binding

• Static binding – The compiler determines which method implementation to use in advance– 编译时就确定了要调用的方法– C++

• Dynamic binding(late binding, virtual binding) – The compiler can't determine which method implementation to use in

advance– The runtime system (JVM) selects the appropriate method at runtime, based

on the class of the object– 在运行阶段才确定要调用的方法– 是实现多态必不可少– JAVA – RTTI

Page 36: Object-Oriented Design and Programming (Java)

36

Method-Call Binding

• The runtime system discovers the type of object sent to computeVolume():– if it’s a Wagon object, Wagon’s computeVolume() is

called

– if it’s a Tank object, Tank’s computeVolume() is called

Page 37: Object-Oriented Design and Programming (Java)

37

Topics Covered Today

• 2.3 Advanced Class Design– 2.3.1 Abstract Classes (抽象类 )– 2.3.2 Polymorphism (多态 )– 2.3.3 Interfaces(接口 )

Page 38: Object-Oriented Design and Programming (Java)

38

Interface

• An interface is collection of constants and abstract methods.

• Syntax:

interface interface_name {

constant -declarations;

abstract methods;

}

Page 39: Object-Oriented Design and Programming (Java)

39

Example

• All methods in an interface are implicitly public and abstract.

• All data fields in an interface are implicitly public, static, and final.

public interface MyInterface { int CONSTANT = 10; void methodOne(); double methodTwo(); void methodThree(double value); }

Page 40: Object-Oriented Design and Programming (Java)

40

Technical Details

• Use the interface keyword rather than class. An Interface usually sits in its own .java file.

• Use public or nothing, private and protected aren’t allowed.

• To implement, write a class using the implements keyword.

• Interface methods are always public.• You can inherit from an interface to create a new

interface.• A single class can implement several interfaces

simultaneously (Java’s version of multiple inheritance).

Page 41: Object-Oriented Design and Programming (Java)

41

Interface Implementationpublic class ClassA implements MyInterface { public void methodOne() { ... }

public double methodTwo() { ... }

public void methodThree(double value) { ... } }

Page 42: Object-Oriented Design and Programming (Java)

42

A Class Implements an Interface

• When a class implements an interface, it agrees to implement all methods in the interface.

• If the class does not implement all the methods, the class must be defined as abstract.

Page 43: Object-Oriented Design and Programming (Java)

43

Inherit form an interface

• An interface can extend another interface

public interface MyInterface extends InterfaceOne {

void aMethod();

}

Page 44: Object-Oriented Design and Programming (Java)

44

interface can extend several interfaces

public interface MyInterface extends InterfaceOne, InterfaceTwo { void aMethod(); }

Page 45: Object-Oriented Design and Programming (Java)

45

A class can implements several interfaces

public class ClassA implements Interface1, Interface2, Interface3 { ... }

Page 46: Object-Oriented Design and Programming (Java)

46

UML Representation of Interfaces

+methodOne()

+methodTwo() : double

+methodThree(newValue : double)

<<interface>>

MyInterface

+methodOne()

+methodTwo() : double

+methodThree(newValue : double)

ClassA

+methodOne()

+methodTwo() : double

+methodThree(newValue : double)

ClassB

Page 47: Object-Oriented Design and Programming (Java)

47

UML Representation of Interfaces

Page 48: Object-Oriented Design and Programming (Java)

48

Case Study

+turnon()

+turnoff()

<<interface>>

Device

+turnon()

+turnoff()

DeviceDemo

+turnon()

+turnoff()

Stopwatch

Page 49: Object-Oriented Design and Programming (Java)

49

Interface Device

public interface Device {

/**

* Turns the device off.

*/

void turnOff();

/**

* Turns the device on.

*/

void turnOn();

}

Page 50: Object-Oriented Design and Programming (Java)

50

Class DeviceDemoimport java.io.*;public class DeviceDemo implements Device {

private static PrintWriter stdOut = new PrintWriter(System.out, true);private String name;

public static void main (String[] args) {Device device = new DeviceDemo("demo"); device.turnOn();

device.turnOff(); }

public DeviceDemo (String initialName) {name = initialName;

}

public void turnOff() {stdOut.println("Turn off device " + name);

}

public void turnOn() { stdOut.println("Turn on device " + name);

}}

Page 51: Object-Oriented Design and Programming (Java)

51

Class Stopwatch import java.io.*;public class Stopwatch implements Device {

public static final int OFF = 0; public static final int ON = 1;

private static PrintWriter stdOut = new PrintWriter(System.out, true);

private int state;private long startTime;

public Stopwatch () { state = Stopwatch.OFF; startTime = 0; }

Page 52: Object-Oriented Design and Programming (Java)

52

Class Stopwatch public void turnOn() {

startTime = System.currentTimeMillis();state = Stopwatch.ON;

}

public void turnOff() {if (state == Stopwatch.OFF) {

stdOut.println("The device is off");} else {

long rightNow = System.currentTimeMillis(); stdOut.println("Time: " + (rightNow - startTime));startTime = 0;state = Stopwatch.OFF;

} }

Page 53: Object-Oriented Design and Programming (Java)

53

Class DeviceDemopublic static void main (String[] args) {

Device device = new Stopwatch();

device.turnOn();

for (int i = 0; i < 50000000; i++);

device.turnOff(); }

}

Page 54: Object-Oriented Design and Programming (Java)

54

Comparing Abstract Classes and Interfaces

• An abstract class can define instance variables, whereas an interface cannot.

• An abstract class can implement methods, whereas an interface cannot.

• Interfaces do not contain constructors. • If a class extends an abstract class, it cannot extend

another class; if a class implements an interface, it is free to extend another class and implement many other interfaces.

Page 55: Object-Oriented Design and Programming (Java)

55

Why do we use Interfaces?.

• To reveal an object's programming interface (functionality of the object) without revealing its implementation– This is the concept of encapsulation– The implementation can change without affecting the

caller of the interface– The caller does not need the implementation at the

compile time• It needs only the interface at the compile time

• During runtime, actual object instance is associated with the interface type

Page 56: Object-Oriented Design and Programming (Java)

56

Why do we use Interfaces?..

• To have unrelated classes implement similar methods (behaviors)– One class is not a sub-class of another

• Example:– Class Line and class MyInteger

• They are not related through inheritance• You want both to implement comparison methods

– checkIsGreater(Object x, Object y)– checkIsLess(Object x, Object y)– checkIsEqual(Object x, Object y)

– Define Comparison interface which has the three abstract methods above

Page 57: Object-Oriented Design and Programming (Java)

57

Why do we use Interfaces?...

• To model multiple inheritance – A class can implement multiple interfaces while it can

extend only one class

Page 58: Object-Oriented Design and Programming (Java)

58

Interface as a Type

• When you define a new interface, you are defining a new reference type

• You can use interface names anywhere you can use any other type name

• If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface

Page 59: Object-Oriented Design and Programming (Java)

59

Example: Interface as a Type

• Let's say Person class implements PersonInterface interface

• You can do:– Person p1 = new Person();– PersonInterface pi1 = p1;– PersonInterface pi2 = new Person();

Page 60: Object-Oriented Design and Programming (Java)

60

Interface and Polymorphism

• Interfaces exhibit polymorphism as well, since program may call an interface method, and the proper version of that method will be executed depending on the type of object instance passed to the interface method call

Page 61: Object-Oriented Design and Programming (Java)

61

Rewriting Interfaces

• Problem of Rewriting an Existing Interface

Page 62: Object-Oriented Design and Programming (Java)

62

Solution of Rewriting an Existing Interface