java @ch11. inheritance and polymorphism 2010.12.31
Post on 21-Dec-2015
233 Views
Preview:
TRANSCRIPT
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
HPMP
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
HPMP
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): voidadd(index: int, o: object): voidclear(): voidindexOf(o: object): intisEmpty(): booleanlastIndexOf(o: object): intremove(o: obect): booleansize(): int
Java.util.ArrayList
程式範例 :
TestArrayList.java
top related