Java
@Ch11. Inheritance and Polymorphism
2010.12.31
Outline
•
Inheritance
•
Superclasses and Subclasses
•
Using
super
keyword
•
Overiding Method
•
Overiding vs. Overloading
•
Dynamic Binding
•
Polymorphism
[Sample code]
Novice
.java
、
Magician
.java
、
Swordman
.java
、
Game.java
DynamicBindingDemo.java
Inheritance
•
Object-oriented programming allows you to derive
new classes from existing classes. This is called
inheritance
.
Superclasses and Subclasses
HP
MP
magic_attack()
power_attack()
Novice
Magician
Swordman
attack()
inheritance
inheritance
程式範例
:
Novice
.java
、
Magician
.java
、
Swordman
.java
、
Game.java
Using
super
keyword
•
The
super
refers to the superclass of the class in which super
appears.
•
It can be used in two ways:
1. To call a superclass constructor.
2. To call a superclass method.
Overiding Method
HP
MP
Novice
attack()
attack()
Archer
inheritance
overriding
程式範例
:
Archer.java
Overiding vs. Overloading
•
Overriding
覆寫
Sometimes it is necessary for the subclass to modify the
implementation of a method defined in the superclass.
•
Overloading
多載
Define multiple methods with the same name but different
signature .
(
課本
p.407)
Dynamic Binding
•
Dynamic Binding
動態載入
物件的行為並不是在編譯時期
(compiler-time)
就已經
決定了。而是在程式執行時期於
(run-time)
才動態地決定
的。如何動態地決定。就看物件當時的狀態
(state)
而定,
物件封裝了所有可能的狀態處理
方法,並且根據外邊送
來的訊息做出適當的反應。
(
課本
p.409)
程式範例
:
DynamicBindingDemo.java
程式範例
:
DynamicBindingDemo.java
Polymorphism
•
Polymorphism
多型
簡單來說,多型是指一個物件可以擁有多個不同的型
態,而這些型態必須是該物件所繼承的其他類別。
Organism O = new Organism();
People P = new People();
Organism O2 = new People();
生物
動物
人
extends
extends
•
Polymorphism
- Overriding
- Overloading
- Dynamic binding
- Interface/abstract
ArrayList
•
ArrayList
class that can be used to store an unlimited number
of objects.
add(o object): void
add(index: int, o: object): void
clear(): void
indexOf(o: object): int
isEmpty(): boolean
lastIndexOf(o: object): int
remove(o: obect): boolean
size(): int
Java.util.ArrayList
程式範例
:
TestArrayList.java