• No results found

Object-Oriented Programming: Polymorphism

N/A
N/A
Protected

Academic year: 2021

Share "Object-Oriented Programming: Polymorphism"

Copied!
16
0
0

Loading.... (view fulltext now)

Full text

(1)

1992-2007 Pearson Education, Inc. All rights reserved.

10

10

Object-Oriented

Programming:

Polymorphism

2 

10.3

Demonstrating Polymorphic

Behavior

10.4

Abstract Classes

and Methods

10.5

Case Study: Payroll System Using

Polymorphism

10.6

final

Methods and Classes

(2)

1992-2007 Pearson Education, Inc. All rights reserved.

10.3

Demonstrating Polymorphic

Behavior

A superclass reference can be aimed at a subclass

object (i.e., 調用不同子類別的method)

This is possible because a subclass object is asuperclass object as well

When invoking a method from that reference, the type of the actual referenced object, not the type of the reference, determines which method is called

The same method name and signature can cause different actions to occur, depending on the type of object on which the method is invoked (to write a more general program)

4

class Vehicle {

public void start()

{

System.out.println("Starting ..."); }

}

class Jet extends Vehicle {

public void start()

{

System.out.println("2nd Starting ..."); }

public void zoom() { System.out.println("zooming ...");

Concept of Polymorphism

Vehicle Jet Is-A

(3)

1992-2007 Pearson Education, Inc. All rights reserved. class App232

{

public static void main(String[] args) {

Vehiclej = new Jet();

j.start(); // aims to method of subclassflexibility

//j.zoom(); error: cann't find symbol

} }



> 2nd Starting ... 6 

–設計方法display(obj),其參數obj可以是Whierlybird, Aircraft, or Jet

類別的物件,並顯示物件obj所有field的值 • Alternative 1. entirely 3 versions of display()

• Alternative 2. only 1 versions of display()

Exercise

Vehicle Aircraft Whirlybird Jet a1 a2 b1 c1 c2 c3 Is-A

(4)

1992-2007 Pearson Education, Inc. All rights reserved. CommissionEmploy3 - baseSalary BasePlusCommissionEmploy4 See Fig 9.12, 9.13 + toString(): double + toString(): double

2nd Polymorphism Example

Fig 10.1

8

10.4

Abstract Classes and Methods

Abstract classes

Used only as abstract superclasses for concrete subclasses and to declare reference variables

Keyword abstract (see Fig. 10-4)Use to declare a class abstract

Also use to declare a method abstract

Abstract classes normally contain one or more abstract methods

All concrete subclasses must override all inherited abstract methods

(5)

1992-2007 Pearson Education, Inc. All rights reserved. Fig. 10.2 | Employeehierarchy UML class diagram.

Extract common members

Differ in earning() and toString() For Fig 10.4 ~ 10.8 - weeklySalary - firstName - lastName - securityNumber - wage - hours - grossSales - commissionRate - baseSalary 10 

下面的程式中,在抽象類別CShape裡已定義好一個show(),以及一個abstract method。 請在CWin類別裡撰寫area() method的定義,使得我們可以利用CWin類別來顯示物件的

widthheight與面積。例如,在第24行建立CWin類別的物件win後,便可利用它來執行 第25行的呼叫。

01 // hw11_2, 抽象類別

02 abstract class CShape

03 {

04 protected int width;

05 protected int height;

06

07 public void show()

08 {

09 System.out.println("width="+width);

10 System.out.println("height="+height);

11 System.out.println("area="+area());

12 }

13 public abstract int area(); // 計算面積

14 }

(6)

1992-2007 Pearson Education, Inc. All rights reserved.

15 class CWin extends CShape 16 { 17 // 請完成這個部分的程式碼 18 } 19 20 public class hw11_2 21 {

22 public static void main(String args[])

23 {

24 CWin win=new CWin(5,7); // 建立CWin類別的物件

25 win.show();

26 }

27 }

12

10.5 Case Study: Payroll System

Using Polymorphism

(7)

1992-2007 Pearson Education, Inc. All rights reserved.

Dynamic binding

Calls to overridden methods are resolved at execution time, based on the type of object referenced

Downcasting

Convert a reference to a superclass to a reference to a subclass

Allowed only if the object has an is-a relationship with the subclass

The same method name and signature can cause

different actions to occur, depending on the type

of object on which the method is invoked (to write

a more general program)

14

Summary of the Allowed

Assignments

Superclass and subclass assignment rules

Assigning a superclass reference (i.e., object instance) to a superclass variable (i.e., object reference) is

straightforward

Assigning a subclass reference to a subclass variable is straightforward

Assigning a subclass reference to a superclass variable is safe because of the is-a relationship

Referring to subclass-only members through superclass variables is a compilation error

Assigning a superclass reference to a subclass variable is a compilation error

(8)

1992-2007 Pearson Education, Inc. All rights reserved.

10.6

final

Methods and Classes

final

methods

Cannot be overriddenin a subclass

privateand staticmethods are implicitly finalfinalmethods are resolved at compile time, this is known

as static binding

final

classes

Cannot be extendedby a subclass

All methods in a finalclass are implicitly final

16

class animal {

final void breathe() {

System.out.println("Breathing ..."); }

}

class fish extends animal {

public void breathe() {

System.out.println("Bubbling ..."); }

}

(9)

1992-2007 Pearson Education, Inc. All rights reserved. final class animal

{

public void breathe() {

System.out.println("Breathing ..."); }

}

class fish extends animal {

public void breathe() { System.out.println("Bubbling ..."); } }

Final (2)

18  class app242 {

public static void main(String[] args) { final int a = 5; a = 6; } } > 1 error

Cannot assign a value to final variable a

Final (3)

(10)

1992-2007 Pearson Education, Inc. All rights reserved.

10.7

Case Study: Creating and Using

Interfaces

Interfaces

Keyword interface

Contains only constants and abstractmethodsAll fields are implicitly public, staticand final

All methods are implicitly public abstractmethodsTypically used when disparate (不同的) classes need to

share common methods and constants

20

Interface (1)

import java.io.*;

interface Vehicle // No method-definitions

{

public void startEngine(); public void stopEngine(); }

interface Asset // No method-definitions

{

public int initialCost(); public int currentCost(); }

• 在C++中可以使用多重繼承,但在

Java中只能單一繼承,也就是一次 只能擴充一個類別,Java使用

(11)

1992-2007 Pearson Education, Inc. All rights reserved. public class int01 implements Vehicle, Asset

{

public void startEngine() // no overriding among interfaces

{

System.out.println("aaa"); }

public void stopEngine() {

System.out.println("bbb"); }

public int initialCost() {

return 2; }

public int currentCost() {

return 3; }

extends class-A implements class-B

22

public static void main(String args[]) {

int01 a = new int01(); a.startEngine(); a.stopEngine(); System.out.println(a.initialCost()); System.out.println(a.currentCost()); } } aaa bbb 2 3

(12)

1992-2007 Pearson Education, Inc. All rights reserved.

Interface (2)

interface iShape {

final double PI=3.14;

abstract void setColor(String str); }

interface iShape2D extends iShape {

abstract void area(); }

24

class CCircleimplementsiShape2D { double radius; String color; public CCircle(double r) { radius=r; }

public void setColor(String str) { color=str;

System.out.println("color="+color); }

public void area() {

(13)

1992-2007 Pearson Education, Inc. All rights reserved. public class app11_7

{

public static void main(String args[]) { CCircle cir; cir=new CCircle(2.0); cir.setColor("Blue"); cir.area(); } } 26  下面的程式碼是修改自習題1,其中把抽象類別CShape改以介面來宣告。

請在CWin類別裡撰寫show() area() method的定義,使得我們可以利用CWin類別 來顯示物件的widthheight與面積。

01 // hw11_5, 介面實作

02 interface iShape 03 {

04 public void show();

05 public int area(); // 計算面積

06 }

(14)

1992-2007 Pearson Education, Inc. All rights reserved.

07 class CWin implements iShape 08 {

09 protected int width; 10 protected int height; 11 12 // 請完成這個部分的程式碼 13 } 14 15 public class hw11_5 16 {

17 public static void main(String args[]) 18 {

19 CWin win=new CWin(5,7); // 建立CWin類別的物件 20 win.show();

21 } 22 }

28

下面的程式碼是修改自習題3,其中增加了一個iColor介面。iColor介面裡定義了1method

public void showColor();// 顯示顏色

請在CWin類別裡撰寫showColor() method的定義,使得我們可以利用CWin類別來顯示 物件的顏色、widthheight與面積。

01 // hw11_9, 多重繼承的練習

02 interface iShape 03 {

04 public void show();

05 public int area();

06 }

07 interface iColor 08 {

09 public void showColor();

10 }

(15)

1992-2007 Pearson Education, Inc. All rights reserved.

11 class CWin implements iShape,iColor 12 { 13 // 請完成這個部分的程式碼 14 } 15 16 public class hw11_9 17 {

18 public static void main(String args[]) 19 {

20 CWin win=new CWin(5,7,"Green"); 21 win.show(); 22 } 23 } 30  realization Fig 10.11 – 10.15 發票

(16)

1992-2007 Pearson Education, Inc. All rights reserved.

10.7.7 Declaring Constants with

Interfaces

Interfaces can be used to declare constants used

in many class declarations

These constants are implicitly public, staticand final

Using a static importdeclaration allows clients to use these constants with just their names

A reference to a subclass object can be assigned

to an interface variable if the superclass

References

Related documents

Please note that costs for Sections 18004(a)(2) and (a)(3) funds may only be used “to defray expenses, including lost revenue, reimbursement for expenses already incurred,

 Emergency core cooling system via the steam generators – cools down the reactor core upon loss of power and loss of coolant in the primary or secondary circuit. In the event

The genomic features enriched in CNVs (homologous regions, masked regions, CpG sites, TSSs and AT-rich intervals) support specific mechanisms of the formation of CNVs.. Moreover,

And return a variable, to a pointer types used in a value can be assumed transient object, or two different boxes are not possible for.. One key difference is that references

Content Outline: This session examines the different ways to evaluate technologies for young children, focusing on the different factors, in particular the role of adults, which

different outcomes in these two cases are consistent with the argument presented in this dissertation: initial elections in one of the cases resulted in a better reflection of

10.12 (Optional) Discovering Design Patterns: Introducing Creational, Structural and Behavioral Design Patterns.. 10.12.1 Creational Design Patterns 10.12.2 Structural

– Object based programming (classes, objects, encapsulation) – Object oriented programming (inheritance, polymorphism) – Generic programming (class and function templates)...