版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、繼承與多態(tài) 劉 欽 南京大學(xué)軟件學(xué)院 Outline 繼承 多態(tài) 繼承vs組合 繼承和構(gòu)造方法繼承 A Case for InheritanceSpec:Animal simulation program Weve been given a list of some of the animals that will be in the program, but not all. Each animal will be represented by anobject. We want other programmers to be able to add new kinds of animals
2、 to the program at any time. 5. Finish the class hierarchy Feline class and Canineclass Felines could use a commonroam().Inheritance treeWhich method is called?Which method is called? When you call a method on an object reference, youre calling the most specific versionofthemethodforthatobjecttype.
3、“Lowest” on the inheritancetree.Using IS-A and HAS-A When one class inherits from another, we say that the subclass extends the superclass. When you want to know if one thing should extend another, apply the IS-A test.HAS-ATransitive LawWhen designing with inheritanceis-a vs is-like-a Is-ais-like-aQ
4、:What are the benefits ofinheritance? A: One of the keybenefits of inheritance is to minimise the amount of duplicate code in an application by sharing common code amongst several subclasses. Inheritance can also make application code more flexible to change because classes that inherit from a commo
5、n superclass can be used interchangeably.Q:What forms of inheritance aresupportedby Java? A:The standard form of inheritance is by extension The second special form of inheritance is where classes declare that they implement an interface, which has more limited consequences.Q: Can you show examples
6、of Java inheritance? A: An example of inheritance using the extends keyword would be the java.util.Stack class that extends the Vector class to provide a last-in-first-out stack of Objects. The Stack class uses the same underlying storage facilities provided by the superclass and adds its own, so it
7、 is a type of Vector and behaves like a specialised wrapper around the Vector class. The Stack class adds a boolean empty() method, peek(), pop() and push() methods to manage the stack contents and a search() method to find the index of a given object. All the original methods of the Vectorclass rem
8、ain and the Stack can be cast to a Vector as necessary.Benefits of inheritance多態(tài) A weird phenomenon Wolf aWolf = new Wolf(); Animal aHippo = new Hippo(); It is weird: Animal anim = new Animal();The new hierarchyAbstract methodsNo Abstract Method in a Non-Abstract ClassImplement abstract methods Abst
9、ract methods exist solely for polymorphism. A concrete class must implement all abstract methods. Implementing an abstract method is just like overriding a method.Building the Dog-specific list問(wèn)題 動(dòng)物的Arraylist 每個(gè)動(dòng)物對(duì)象表現(xiàn)下他們的行為 新的一種動(dòng)物加入進(jìn)來(lái) If we need to keepCats? Make a separate classMyCatList? Make an a
10、nimal list to take any kind ofanimals. We dont have a superclass for Animal? Every class in Java extends class Object, without you ever having to say it. You can think of it as though a class you write looks like: Public class Dog extends Object The compiler decides whether you can call a method bas
11、ed on the reference type, not the actual object type. The compiler checks the class of the reference type not the object type to see if you can call a method using thatreference. The JVM decides which actual method is called based on the actual object type.Inner Object An object contains everything
12、it inherits from each of its superclasses. That means every object regardless of its actual class type is also an instance of class Object. Dog example多態(tài)的思想 多態(tài)通過(guò)分離“做什么”和“怎么做”,從另一角度將接口和實(shí)現(xiàn)分離開來(lái)。 多態(tài)不但能夠改善代碼的組織結(jié)構(gòu)和可讀性,還能夠創(chuàng)建“可擴(kuò)展的”程 序, 即無(wú)論在項(xiàng)目最初創(chuàng)建時(shí),還是在需要添加新功能時(shí),都可以進(jìn)行擴(kuò) 充。 更容易理解。而多態(tài)的作用則是消除類型之間的耦合關(guān)系多態(tài)方法調(diào)用允 許一種類型
13、表現(xiàn)出與其他相似類型之間的區(qū)別,只要它們都是從同一基類 導(dǎo)出而來(lái)的。這種區(qū)別是根據(jù)方法行為的不同來(lái)而表示出來(lái)的,雖然這些方法都可以通過(guò)同一個(gè)基類來(lái)調(diào)用。 多態(tài)的意思是“多種形式”,多種形式的意思是可以出現(xiàn)不同的計(jì)算類型, 并且在運(yùn)行的時(shí)候動(dòng)態(tài)的確定正確的計(jì)算。 多態(tài)是指多個(gè)方法使用同一個(gè)名字有多種解釋,當(dāng)使用這個(gè)名字去調(diào)用方 法時(shí),系統(tǒng)將選擇重載自動(dòng)的選擇其中的一個(gè)方法。在多態(tài)中只關(guān)心一個(gè) 對(duì)象做什么,而不關(guān)心如何去做。The Same TypeNot The SameType類型檢查和動(dòng)態(tài)綁定 類型檢查 必須按照方法形參的類型來(lái)檢查消息的參數(shù)類型,必須按消息所期待的類型來(lái)檢查方法的返回類型。
14、 綁定 綁定在程序中的意思是把一個(gè)標(biāo)志符與一個(gè)存儲(chǔ)單元或者把一個(gè)標(biāo)志符與一個(gè)變量,方法建立起聯(lián)系。 動(dòng)態(tài)綁定 在運(yùn)行時(shí),根據(jù)對(duì)象的類型進(jìn)行綁定。Polymorphism - Reference TypePolymorphism Arguments and Return TypeReuse多態(tài) “多態(tài)”意味著“不同的形式”。在面向?qū)ο蟮某绦蛟O(shè)計(jì)中,我們持有相同的外觀(基類的通用接口)以及使用該外觀的 不同形式:不同版本的動(dòng)態(tài)綁定方法。 如果不運(yùn)用數(shù)據(jù)抽象和繼承,就不可能去理解,進(jìn)而也不可 能創(chuàng)建一個(gè)多態(tài)例子。多態(tài)是一種不能單獨(dú)來(lái)看待的特 性(例如,像 switch 語(yǔ)句是可以的),相反它只能作為
15、類關(guān)系“全景”中的一部分,與其它特性協(xié)同工作。 人們經(jīng)常被Java語(yǔ)言中其他的非面向?qū)ο蟮奶匦运_,比 如方法重載等,人們有時(shí)會(huì)被認(rèn)為這些是面向?qū)ο蟮奶?性。但是不要被愚弄:如果不是后期綁定,就不是多態(tài)。 Rules for overridingOverloading陷阱:“overriding”私有法 public class PrivateOverride private static Test monitor = new Test(); private void f() System.out.println(private f(); public static void main(St
16、ring args) PrivateOverride po = new Derived(); po.f(); monitor.expect(new String private f() ); class Derived extends PrivateOverride public void f() System.out.println(public f(); /:這個(gè)呢? class Base public void callFoo() foo(); private void foo() class Child extends Base private void foo() Usage is
17、like the following: Child c = new Child(); c.callFoo();繼承vs組合 繼承和組合的選擇 組合和繼承都允許你在新的類中設(shè)置子對(duì)象(subobject),組合是顯式地這樣做 的,而繼承則是隱式的。InheritanceCompositionThe change Adding a new subclass Inheritance helps make code easier to change Changing the superclass interface one little change to a superclass can rippl
18、e out and require changes in many other places in the applicationscode.Code reuse via inheritanceICode reuse via inheritanceIICode reuse via composition ICode reuse via composition IIComparing composition and It is easier to change the interface of a back-end class (composition) than a superclass (i
19、nheritance). As the previous example illustrated, a change to the interface of a back-end class necessitates a change to the front-end class implementation, but not necessarily the front-end interface. Code that depends only on the front-end interface still works, so long as the front-end interface
20、remains the same. By contrast, a change to a superclasss interface can not only ripple down the inheritance hierarchy to subclasses, but can also ripple out to code that uses just the subclasss interface. It is easier to change the interface of a front-end class (composition) than a subclass (inheri
21、tance). Just as superclasses can be fragile, subclasses can be rigid.You cant just change a subclasss interface without making sure the subclasss new interface is compatible with that of its supertypes. For example, you cant add to a subclass a method with the same signature but a different return t
22、ype as a method inherited froma superclass. Composition, on the other hand, allows you to change the interface of a front-end class without affecting back-end classes. Composition allows you to delay the creation of back-end objects until (and unless) they are needed, as well as changing the back-en
23、d objects dynamically throughout the lifetime of the front-end object. With inheritance, you get the image of the superclass in your subclass object image as soon as the subclass is created, and it remains part of the subclass object throughout the lifetime of the subclass. It is easier to add new s
24、ubclasses (inheritance) than it is to add new front-end classes (composition), because inheritance comes with polymorphism. If you have a bit of code that relies only on a superclass interface, that code can work with a new subclass without change.This is not true of composition, unless you use comp
25、osition with interfaces. Used together, composition and interfaces make a very powerful design tool. The explicit method-invocation forwarding (or delegation) approach of composition will often have a performance cost as compared to inheritances single invocation of an inherited superclass method im
26、plementation. I say often here because the performance reallydependsonmany factors,including how the JVM optimizes the program as it executes it. With both composition and inheritance, changing the implementation (not the interface) of any class is easy. The ripple effect of implementation changes r
27、emain inside the same class.Choosing between inheritance andcomposition Make sure inheritance models the is-a relationship Dont use inheritance just to get code reuse Dont use inheritance just to getat polymorphism組合的選擇 組合技術(shù)通常用于你想要在新類中使用現(xiàn)有類的功能而非它的接口的情形。即,你在新類中嵌入某個(gè)對(duì)象,借其實(shí)現(xiàn)你所需要的功能,但新類的用戶看到的只是你為新類所定義的接口
28、,而非嵌入對(duì)象的接口。為取得此效果,你需要在新類中嵌入一個(gè) private 的現(xiàn)有類的對(duì)象。 有時(shí),允許類的用戶直接訪問(wèn)新類中的組合成份是極具意義的;也就是說(shuō),將成員對(duì)象聲明為 public。如果成員對(duì)象自身都實(shí)現(xiàn)了具體實(shí)現(xiàn)的隱藏,那么這種做法就是安全 的。當(dāng)用戶能夠了解到你在組裝一組部件時(shí),會(huì)使得端口 更加易于理解。 Car對(duì)象即為一個(gè)好例子:Car /: c06:Car.java / Composition with public objects. class Engine public void start() public void rev() public void stop() c
29、lass Wheel public void inflate(int psi) class Window public void rollup() public void rolldown() class Door public Window window = newWindow(); public void open() public void close() public class Car public Engine engine = new Engine(); public Wheel wheel = new Wheel4; public Door left = new Door(),
30、 right = new Door(); / 2-door public Car() for(int i = 0; i 4;i+) wheeli = new Wheel(); public static void main(String args) Car car = new Car(); car.left.window.rollup(); car.wheel0.inflate(72); /:繼承和構(gòu)造方法 Inheritance and constructorsHow to invoke a superclass constructor?Superclass constructor with
31、 argumentsInvoking one overloaded constructor from anotherInitialization with inheritance Access Main(), load base class, Load until the root base class Static Initialization in the root base class then the next derived class, and so on All the primitives and the object reference areset to null The
32、base-class constructor will becalled The instance variables are initialized in textual order The rest of the body of the constructor is executed class Characteristic private String s; Characteristic(String s) this.s = s; System.out.println(Creating Characteristic + s); protected void dispose() Syste
33、m.out.println(finalizing Characteristic + s); class Description private String s; Description(String s) this.s = s; System.out.println(Creating Description + s); protected void dispose() System.out.println(finalizing Description + s); class LivingCreature private Characteristic p = new Characteristi
34、c(is alive); private Description t = new Description(Basic Living Creature); LivingCreature() System.out.println(LivingCreature(); protected void dispose() System.out.println(LivingCreature dispose); t.dispose(); p.dispose(); class Animal extends LivingCreature private Characteristic p= new Characte
35、ristic(has heart); private Description t = new Description(Animal not Vegetable); Animal() System.out.println(Animal(); protected void dispose() System.out.println(Animal dispose); t.dispose(); p.dispose(); super.dispose(); class Amphibian extends Animal private Characteristic p = new Characteristic
36、(can live in water); private Description t = new Description(Both water and land); Amphibian() System.out.println(Amphibian(); protected void dispose() System.out.println(Amphibian dispose); t.dispose(); p.dispose(); super.dispose(); public class Frog extends Amphibian private static Test monitor =
37、new Test(); private Characteristic p = new Characteristic(Croaks); private Description t = new Description(Eats Bugs); public Frog() System.out.println(Frog(); protected void dispose() System.out.println(Frog dispose); t.dispose(); p.dispose(); super.dispose(); public static void main(String args) F
38、rog frog = new Frog(); System.out.println(Bye!); frog.dispose(); monitor.expect(new String Creating Characteristic is alive, Creating Description Basic Living Creature, LivingCreature(), Creating Characteristic has heart, Creating Description Animal not Vegetable, Animal(), Creating Characteristic can live in water, Creating Description Both water and land, Amphibian(), Creating Characteristic Croaks, Creating Description Eats Bugs, Frog()
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年區(qū)塊鏈技術(shù)應(yīng)用與安全指南
- 2025年企業(yè)財(cái)務(wù)報(bào)表編制與審核規(guī)范-2
- 財(cái)務(wù)人員崗位責(zé)任制與考核制度
- 辦公室員工培訓(xùn)效果持續(xù)改進(jìn)制度
- 辦公室環(huán)境衛(wèi)生維護(hù)制度
- 養(yǎng)老院環(huán)境清潔制度
- 2026年濰坊市教育局所屬學(xué)校急需緊缺人才及部屬公費(fèi)師范生公開招聘?jìng)淇碱}庫(kù)附答案詳解
- 2026年綿陽(yáng)東風(fēng)南方汽車銷售有限公司招聘?jìng)淇碱}庫(kù)完整答案詳解
- 2026年湖南省茶業(yè)集團(tuán)股份有限公司招聘?jìng)淇碱}庫(kù)及一套答案詳解
- 云南特殊教育職業(yè)學(xué)院2026年春季銀齡教師招募備考題庫(kù)及答案詳解一套
- 2026年上海市松江區(qū)初三語(yǔ)文一模試卷(暫無(wú)答案)
- 清華大學(xué)教師教學(xué)檔案袋制度
- 公租房完整租賃合同范本
- 東南大學(xué)附屬中大醫(yī)院2026年招聘?jìng)淇碱}庫(kù)及答案詳解參考
- 2025新疆阿瓦提縣招聘警務(wù)輔助人員120人參考筆試題庫(kù)及答案解析
- 貴州國(guó)企招聘:2025貴州鹽業(yè)(集團(tuán))有限責(zé)任公司貴陽(yáng)分公司招聘考試題庫(kù)附答案
- 2025-2026學(xué)年秋季學(xué)期教學(xué)副校長(zhǎng)工作述職報(bào)告
- GB/T 3098.5-2025緊固件機(jī)械性能第5部分:自攻螺釘
- 2026年安徽國(guó)防科技職業(yè)學(xué)院?jiǎn)握新殬I(yè)適應(yīng)性考試題庫(kù)及完整答案詳解1套
- 2026年服裝電商直播轉(zhuǎn)化技巧
- 2025秋粵教粵科版(新教材)小學(xué)科學(xué)二年級(jí)上冊(cè)知識(shí)點(diǎn)及期末測(cè)試卷及答案
評(píng)論
0/150
提交評(píng)論