




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
1、Java面向對象思想和概念 1JavaClasses and Objects1目標 掌握面向對象編程的概念掌握如何創(chuàng)建類和構造對象掌握對象的成員變量和方法了解this關鍵字2面向對象編程概述面向對象編程(Object Oriented Programming,簡稱OOP)描述的是對象之間的相互作用。面向對象編程與面向過程編程的區(qū)別過程化程序設計先確定算法,再確定數(shù)據(jù)結構;面向對象編程先確定數(shù)據(jù)結構,再確定運算。面向過程編程的程序員,習慣于建立數(shù)據(jù)結構存放數(shù)據(jù)并定義方法(函數(shù))來操作數(shù)據(jù);面向對象編程的程序員則構造一個對象模型,將數(shù)據(jù)與方法組織在一起。3對象 對象的狀態(tài) 對象的行為我們可以把現(xiàn)實
2、世界的事物抽象成對象 對象一般都有兩個特征: 狀態(tài)(state)和行為(behavior)軟件的對象概念是由現(xiàn)實世界對象抽象而來 把現(xiàn)實世界對象的狀態(tài)保存在軟件對象的變量中;現(xiàn)實世界對象的行為通過軟件對象的方法(函數(shù))來實現(xiàn)。4面向對象OOAObject Oriented Analysis 面向對象的分析OODObject Oriented Design 面向對象的設計OOIObject Oriented Implementation 面向對象的實現(xiàn)5面向對象編程( Object Oriented Programming )class Car int color_number; int doo
3、r_number; int speed; void brake() void speedUp() ; void slowDown() 計算機中的對象的原型現(xiàn)實生活中的對象6什么是類(What Is Class)類實際上是對某種類型的對象定義變量和方法的原型。 在現(xiàn)實世界中,你經??吹较嗤愋偷脑S多對象。比如 ,你的自行車只是現(xiàn)實世界中許多自行車的其中一輛。使用面向對象技術,我們可以說你的自行車是自行車對象類的一個實例。通常,自行車有一些狀態(tài)(當前檔位、兩個輪子等等)以及行為(改變檔位、剎車等等)。但是,每輛自行車的狀態(tài)都是獨立的并且跟其它自行車不同。當廠家制造自行車的時候,廠商利用了自行車共有
4、的特性來根據(jù)相同的藍圖制造許多自行車。如果制造一輛自行車就要產生一個新藍圖,那效率就太低了7對象和類(Objects and Classes)把相似的對象劃歸成一個類。在軟件中,類,就是一個模板,它定義了通用于一個特定種類的所有對象的狀態(tài)(變量)和行為(方法)。類是創(chuàng)建對象的模板,對象是類的實例。一個對象是類的一個實例。有了類,才可以創(chuàng)建對象。類不能是它們描述的對象本身,類是同一種對象的集合的抽象,即,同一類對象的變量和方法的原型。 variablesmethods8面向對象程序設計( Object Oriented Programming ) 從程序設計的角度看,類是面向對象程序中最基本的程
5、序單元。類實質上定義的是一種數(shù)據(jù)類型,這種數(shù)據(jù)類型就是對象類型 。所以我們可以使用類名稱來聲明對象變量。聲明對象變量之后,還不能使用對象。必須用運算符new創(chuàng)建對象實體之后,才能使用對象。9一個簡單的例子編寫一個駕駛汽車的方法面向過程的程序設計: 編寫一個方法,void drivecar();面向對象的程序設計: 將一輛汽車看成一個對象,將所有汽車對象的共性抽取出來,設計一個類Car,類中有一個方法void drive(),用Car這個類實例化一個具體的對象car,調用:car.drive()。10面向對象的三個特征封裝(Encapsulation)繼承(Inheritance)多態(tài)(Poly
6、morphism)11封裝(Encapsulation)封裝把對象的所有組成部分組合在一起,封裝定義程序如何引用對象的數(shù)據(jù),封裝實際上使用方法將類的數(shù)據(jù)隱藏起來,控制用戶對類的修改和訪問數(shù)據(jù)的程度私有數(shù)據(jù) 方法 方法數(shù)據(jù)對象A對象B公有數(shù)據(jù)12OOP封裝的主要好處13信息隱藏例如,電視內有很多復雜零件,通過各種按鈕將內部的復雜結構給隱藏了。簡化操作只需通過調頻和音量等少量按鈕,就可以操縱電視。程序的基本封裝單元是類,通過類的封裝,既可以將代碼單元化,又達到信息隱藏的目的。13類的定義(Declaration)修飾符 class 類名 繼承父類接口成員變量;構造方法;成員方法;文件名必須與pub
7、lic類名相同;14創(chuàng)建對象使用下列語法可創(chuàng)建對象: new 構造函數(shù)關鍵字 new 通常稱為創(chuàng)建運算符,用于分配對象內存,并將該內存初始化為缺省值。一旦 new 完成分配和初始化內存,它就將調用構造函數(shù)來執(zhí)行對象初始化。當創(chuàng)建一個類時,只是創(chuàng)建了一種新的數(shù)據(jù)類型。對象是類的一個實例。15new1、第一步,你必須聲明該類類型的一個變量,這個變量沒有定義一個對象。實際上,它只是一個能夠引用對象的簡單變量。2、第二步,該聲明要創(chuàng)建一個對象的實際的物理拷貝,并把對于該對象的引用賦給該變量。這是通過使用new運算符實現(xiàn)的。new運算符為對象動態(tài)分配(即在運行時分配)內存空間,并返回對它的一個引用。這個
8、引用或多或少的是new分配給對象的內存地址。然后這個引用被存儲在該變量中。這樣,在Java中,所有的類對象都必須動態(tài)分配。 16示例:public class TestClass int i;float j;TestClass(int m,int n)this.i = m;this.j = n;public static void main(String args) TestClass a;TestClass b = new TestClass(666,99); /new返回對象引用a = b;System.out.println(a.i);17圖解:18給對象引用變量賦值例如:下面的程序段是
9、做什么呢? Box b1 = new Box(); Box b2 = b1;b1和b2將引用同樣的對象。將b1賦值給b2并沒有分配任何內存或對原對象做任何部分的拷貝。由于它們是同一個對象,因此通過變量b2對對象的改變也將影響b1所對應的對象b1 = null; /b1被設置為空,但是b2仍然指向原來的對象。19構造函數(shù)(Constructor)構造函數(shù)是類的一種特殊的方法,主要表現(xiàn):(1)構造函數(shù)的方法名與類名相同。(2)構造函數(shù)沒有返回類型。(3)構造函數(shù)的主要作用是完成對類對象的初始化工作。20構造函數(shù)定義class Box double width; double height; dou
10、ble depth; Box() System.out.println(Constructing Box);width = 10;height = 10;depth = 10; double volume() return width * height * depth; 21默認構造函數(shù)(Default Constructor)默認構造函數(shù)指沒有參數(shù)的構造函數(shù)如果編寫的類沒有構造函數(shù),系統(tǒng)會自動提供一個默認構造函數(shù),它把所有的屬性設為默認值不要構造函數(shù)?試一試?22帶參數(shù)的構造函數(shù)class Box double width; double height; double depth; / 有參
11、數(shù)的構造函數(shù) Box(double w,double h,double d) width = w;height = h;depth = d; double volume() return width * height * depth; 調用:Box mybox1 = new Box(10,20,15);Box mybox2 = new Box(3,6,9);23方法(Methods) 方法是類的主要組成部分。在一個類中,程序的作用體現(xiàn)在方法中。方法是Java語言的基本構件。利用方法可以組成結構良好的程序。本章介紹方法的構成規(guī)則和設計、使用方法的基本要點。24方法的聲明一般的方法聲明可以具有如下
12、形式: 訪問控制符修飾符 返回類型 方法名(參數(shù)表) throws 異常類名表 /方法體如:Double salery ;Public void addSalery(double sal) / 方法執(zhí)行體salery += sal ;修飾符返回類型方法名參數(shù)列表25方法的調用(Method Invoking) 方法是類的一個動態(tài)的屬性,先創(chuàng)建類的一個實例對象,通過對象.方法名來調用方法如: public class Employee public void show() System.out.println(“ Hello ”); public static void main(String
13、args) Employee e = new Employee(); e.show(); 26this關鍵字 this是指向調用對象本身的引用名。 你可以在當前類的類型所允許對象的任何地方將this作為一個引用。 This實際上主要用于2個方面: 1、引用當前對象。 2、使得類的一個構造函數(shù)可以調用類的另一個構造函數(shù)。 對于1,看下面的例子來理解:27public class TestClass int i;float j;TestClass(int m,int n)this.i = m;this.j = n;this.show_Message();/通過this調用類的普通成員方法了void
14、 show_Message()System.out.println(Hello, everyone!);public static void main(String args) TestClass a;TestClass b = new TestClass(666,99);a = b;System.out.println(a.i);28對于this的第二種用法(作用),看以下例子public class Test2 int i;float f;double d;public Test2(int i, float f) this.i = i;this.f = f;public Test2(int
15、 m, float n, double dd) this(m,n); /Invoke another constructorthis.d = dd;29this引用 class Boxdouble width, height, depth ; Public Box(double width,double height,double depth) this.width = width ; this.height = height; this.depth = depth ; 注意: 在這樣的環(huán)境下使用this有時會引起混淆。有些程序員比較小心,不使用和局部變量、正式的自變量同名的隱藏的實例變量。當
16、然,另外的程序員則相反,相信用this來“揭開”與局部變量、自變量同名的實例變量是一個好習慣。這取決于你的愛好 。30Java面向對象思想和概念 231目標掌握包的使用掌握類的成員訪問控制符掌握static掌握final掌握對象的傳遞32包 (package)Java的文件名必須和public的類名相同,為了解決同名的沖突和類的訪問權限的控制,Java提供包(package)來來管理類名空間package語句必須放在Java源文件的第一條語句,指明該文件中定義的類所在的包,他的格式為: package com.iss.java.base ; public class Test 33導入包 im
17、port 為了能夠使用Java API 中已經提供的類或者是我們自己寫的類,需要import語句來導入所需要的類,這樣能更好的解決名字空間的問題,其格式為: package com.iss.example ; import com.iss.java.base.Test ; / 導入Test類 import java.util.* ; / * 導入這個包 / 下面所有的類 public class ImportDemo34類的訪問控制符在定義類的時候,可以用訪問控制符類的訪問控制符為 public 或者 默認1:public :當一個類被聲明為public時,它就具有了被其他包中的類訪問的可能性
18、,只要這些其他包中的類在程序中使用import語句引入public類,就可以訪問和引用這個類。 2: (默認) :缺省訪問控制權規(guī)定,該類只能被同一個包中的類訪問和引用,而不可以被其他包中的類使用,這種訪問特性又稱為包訪問性。3535設計一個程序測試一下類有無public訪問控制符的區(qū)別?36成員訪問控制符除了public和默認可見性修飾符,Java還為類成員提供private和protected修飾符。類的成員變量和方法都有訪問權限的控制,由于類中封裝了數(shù)據(jù)和代碼,包括封裝了其它的類和包,所以java對類成員提供了四種范圍的訪問控制權限的控制,這四種范圍包括:同一類中 同一包中 不同包中的子
19、類 不同包中的非子類 訪問權限則包括: private、默認、protected和public37屬性或方法的訪問權限同一類中同一包中不同包中的子類不同包中的非子類 private Yes 默認 Yes Yes protected Yes Yes Yes public Yes Yes Yes Yes 訪問權限(Yes表示可以訪問)38private類中限定為private的成員(屬性或者方法),只能被這個類本身訪問,即私有訪問控制:它的聲明如下: private String name ; private void showName()注意:不能在方法體內聲明的變量前加任何訪問限制符(包括pr
20、ivate) private void display() private int i ; / 錯誤39protected類中被限定為 protected 的成員變量和成員方法,可以被這個類本身以及它的子類訪問(包括同一包和不同包中的子類都可以訪問)聲明如下: protected String stuName ; protected void showStuName() 40public 類中被限定為 public 的成員,都是公共的,可以被所有的類訪問,它的的訪問權限時最大的,但同時也是最不安全的,一般情況下成員變量都是定義成private的。定義 public String name ;
21、public void showName() 41自己寫個程序測試一下成員變量或成員函數(shù)的訪問權限?42 setor 和 getor在java中,有一種常見的做法,就是將成員變量用private修飾,從而更好的將信息進行封裝和隱藏,在這樣的類中,用getXXX 和setXXX方法對類的屬性進行存取這個方法有以下優(yōu)點:1 屬性用private更好的封裝和隱藏,外部類不能隨意存取和修改2 提供方法來存取對象的屬性,在方法中可以對給定的參數(shù)進行 合法性檢驗3 方法可以用來給出計算后的值4 方法可以完成其他必要的工作(如:清理資源,設定狀態(tài)等)5 只提供getXXX而不提供setXXX,保證屬性的只讀
22、性43示例 class person private int age ; public int getAge() return age ; protected void setAge(int age)If(age0 & age200) this.age = age ; 44非訪問控制符 類,屬性,方法可以擁有若干修飾符,包括訪問控制符和非訪問控制符,我們現(xiàn)在來介紹java常用的非訪問控制符 static final 45 static 關鍵字 static修飾類的成員變量或者方法的時候,表明類的這些成員時屬于整個類的,不屬于任何一個類的具體的對象實例,它不保存在某個對象實例的內存區(qū)間中,而是保
23、存在類的內存區(qū)域的公共存儲單元。換句話說,對于該類的任何一個具體對象而言,靜態(tài)域是一個公共的存儲單元,任何一個對象訪問它都是取得相同的數(shù)據(jù);同樣,任何一個對象去修改它,也都是對同一個內存單元進行修改。46靜態(tài)變量(Static Variable)或類變量(Class Variable) static int age; 聲明為static的變量實質上就是全局變量。不管創(chuàng)建了類的多少實例,整個類中靜態(tài)變量的副本只有一個 (static成員與對象無關)引用靜態(tài)變量的2種方法:1、通過類的任一實例。2、通過類的名稱。47示例public class StaticDemo static int age
24、;void show() System.out.println(Age:+age); public static void main(String args) StaticDemo s = new StaticDemo(); s.age = 10 ; / 通過實例訪問不是一個好方法 s.show(); StaticDemo.age = 20 ; / 通過類訪問 s.show(); /再定義一個對象來訪問類變量看看? 48靜態(tài)方法與靜態(tài)方法相關的幾個要點:類的靜態(tài)方法只能訪問其它的靜態(tài)成員:靜態(tài)變量和靜態(tài)方法既可以在類的實例方法中使用,也可以在類的靜態(tài)方法中使用。但是,實例變量和實例方法(即非靜
25、態(tài)成員)只能在實例方法中使用,不能在靜態(tài)方法中使用,因為靜態(tài)變量和靜態(tài)方法不屬于某個特定的對象。 (理解一下這句話的含義)靜態(tài)方法不能被覆蓋為非靜態(tài)方法靜態(tài)方法中也不能使用this和super class staticDemo static int i = 10; int j = 20 ; public void function() i = i +j; public static void main(String args) j = x ; / 錯誤,不能訪問非靜態(tài)成員 function(); 常見問題:在main方法中訪問類的靜態(tài)成員變量。 例如上例。49 final 關鍵字 final變
26、量實質上是一個常量。 final方法表明子類不能覆蓋此方法。 final類不能被繼承。50final 變量一個變量可以聲明為final,這樣做的目的是阻止它的內容被修改。聲明final變量后,只能被初始化一次,然后就不能對其值進行修改。一個final變量實質上是一個常量class FinalDemo public static void main(String args) final int noChange = 20; noChange = 30; / 錯誤 51final變量的好處效率:聲明 final 字段有助于優(yōu)化器作出更好的優(yōu)化決定,因為如果編譯器知道字段的值不會更改,那么它能安全地
27、在寄存器中高速緩存該值。 安全:使其某部分狀態(tài)不變可以大大簡化開發(fā) ,使得程序更加安全。52final 方法 在方法聲明中使用 final 關鍵字向編譯器表明子類不能覆蓋此方法。class TestFinal final void f() class Further extends TestFinal final void f() / 錯誤,final方法不能被覆蓋 53 final方法的好處安全:將方法聲明為final,那就說明你已經知道這個方法提供的功能已經滿足你要求,不需要進行擴展,并且也不允許任何從此類繼承的類來覆寫這個方法,但是繼承仍然可以繼承這個方法,也就是說可以直接使用。 效率:
28、有一種被稱為inline的機制,它會使你在調用final方法時,直接將方法主體插入到調用處,而不是進行例行的方法調用。54final類聲明為final的類不能被繼承。如果一個類為 final 類,那么它的所有方法都為隱式的 final 方法。final 類示例:final class TestFinal int i = 7; int j = 1; void f() class Further extends TestFinal / 錯誤 不能被繼承55 final類的好處1)效率,但是性能并不是將類或方法聲明為final 的好理由。 2)簡化:不變類對于簡化面向對象程序的設計非常有用不變的對象
29、只需要較少的防御性編碼。 3)安全:防止類的屬性和方法發(fā)生改變。56類中的常量類中的常量是被該類的所有對象共享的,因此,常量應該聲明為final static。例如,Math類中的常量PI是這樣定義的: final static double PI = 3mmutable Objects and ClassesIf the contents of an object cannot be changed once the object is created, the object is called an immutable object and its class i
30、s called an immutable class. If you delete the set method in the Circle class in the preceding example, the class would be immutable because radius is private and cannot be changed without a set method. A class with all private data fields and without mutators is not necessarily immutable. For examp
31、le, the following class Student has all private data fields and no mutators, but it is mutable.并非所有成員變量為private并且沒有修改器方法的類就是不可變的,例如下例:58Examplepublic class BirthDate private int year; private int month; private int day; public BirthDate(int newYear, int newMonth, int newDay) year = newYear; month =
32、newMonth; day = newDay; public void setYear(int newYear) year = newYear; public class Test public static void main(String args) Student student = new Student(111223333, 1970, 5, 3); BirthDate date = student.getBirthDate(); date.setYear(2010); / Now the student birth year is changed! public class Stu
33、dent private int id; private BirthDate birthDate; public Student(int ssn, int year, int month, int day) id = ssn; birthDate = new BirthDate(year, month, day); public int getId() return id; public BirthDate getBirthDate() return birthDate; 59What Class is Immutable?For a class to be immutable, it mus
34、t mark all data fields private and provide no mutator methods and no accessor methods that would return a reference to a mutable data field object.要使一個類成為不可變的,它必須滿足以下要求:1、所有數(shù)據(jù)域都是私有的。2、沒有修改器方法。3、沒有一個訪問器方法,它會返回一個指向可變數(shù)據(jù)域的引用。60Java面向對象思想和概念 361繼承(Inheritance) 繼承實際上是存在于面向對象程序中的兩個類之間的一種關系。 當一個類擁有另一個類的所有數(shù)據(jù)
35、和操作時,就稱這兩個類之間具有繼承關系,private屬性除外 。 被繼承的類稱為父類(parent class)或超類(super class),繼承了父類的所有數(shù)據(jù)和操作的類稱為子類。 使用繼承的主要優(yōu)點是,使得程序結構清晰,減少編碼,減少維護的工作量。 62單繼承和多重繼承 單重繼承是指任何一個類都只有一個單一的父類;多重繼承是指一個類可以有一個以上的父類。支持多重繼承的程序,其結構為復雜的網狀,能更自然地模擬現(xiàn)實世界,但設計、實現(xiàn)都比較復雜。JAVA出于安全、可靠性的考慮,只支持單重繼承。63子類從父類獲得哪些能力?子類繼承父類的屬性(變量)、功能(方法),子類中只 需聲明特有的東西。
36、1)帶private 修飾符的屬性、方法是不能被繼承的。2)帶protected 修飾符的屬性、方法是被繼承的。3)構造方法不能被繼承。但子類構造方法可以用super()或super(parameters)方法調用父類的構造方法,而且super語句必須放在子類構造方法的第一行。 - super 指向該關鍵字所在類的父類。64Java的繼承類的修飾符 class extends ; ; 在定義子類時用extends關鍵字指明新定義類的父類,就在兩個類之間建立了繼承關系。新定義的類稱為子類,它可以從父類那里繼承所有非private的域和方法作為自己的屬性。 65繼承示例 class Student
37、 private int age ; protected String name ; public void showName() System.out.println(Name: + name); public class ExtendsDemo_1 extends Student public static void main(String args) Student s = new ExtendsDemo_1();/以基類為類型,去new一個子類 = “Soft”;/當前對象并沒有定義name屬性, /但通過extends子類繼承了父類的name屬性 s.showName(
38、); 66方法重載(Overloading)由編譯器決定調用那個方法public class Demo public void add(int i,int j) System.out.println(i+j); public void add(float i,float j) System.out.println(i+j); public void add(String s1,String s2) System.out.println(s1+s2); public static void main(String args) Demo d = new Demo(); d.add(1, 2); d
39、.add(2.56f, 7.44f); d.add(Hello, World); 67重載兼容在調用方法時,若沒有找到類型匹配的方法,編譯器會找可以兼容的類型來進行調用,如:int類型可以找到使用double類型的方法:示例 public class Demo public void add(double i,double j) System.out.println(double : + (i+j); public static void main(String args) Demo d = new Demo(); int i = 10 ; int j = 20 ; d.add(i,j); /
40、 可以兼容 68然而,不好的重載兼容,會發(fā)生有歧義的重載:public class AmbiguousOverloading public static void main(String args) System.out.println(max(1, 2); public static double max(int num1, double num2) if (num1 num2) return num1; else return num2; public static double max(double num1, int num2) if (num1 num2) return num1;
41、else return num2; 69構造函數(shù)重載 Java 為每一個類自動提供缺省構造函數(shù) 構造函數(shù)也可以重載,要求使用不同的參數(shù)個數(shù),不同的參數(shù)類型。構造函數(shù)的重載,可以讓用戶用不同的參數(shù)來構造不同的對象。70構造方法的調用示例 class Example int age ; String name ;public Example(int age) this.age = age ; public Example(int age,String name) Example(age) ; / 錯誤 this(age) ; / 正確 71繼承在開發(fā)中的作用 1、繼承允許代碼重用 2、擴展新功能適
42、應新情況 72 super 的使用1、使用super可以調用父類的構造方法: super(傳參數(shù)給從父類繼承而來的成員變量)2、使用super來調用父類的成員方法。 在子類中繼承了父類中的成員方法,一般可以直接通過方法名使用,但是如果在子類中覆蓋了父類的成員方法以后,如果需要在子類內部調用父類中被覆蓋的成員方法時則不能直接調用了,這樣就又需要使用super關鍵字了: super.父類方法(方法參數(shù));3、可使用super來引用父類的成員變量。 在子類中如果引用從父類繼承的成員變量,也可以使用“super.成員變量”來引用,只是一般成員變量的覆蓋是沒有意義的,所以這個時候都可以直接使用成員變量名
43、進行引用,所以這里的super都可以省略。73 調用父類的構造函數(shù) 子類可通過調用super()來調用超類(父類)的構造函數(shù),對從父類繼承而來的成員變量進行初始化。而且,super()必須放在子類構造函數(shù)中的第一行。class Box Box(double width,double heigth,double depth)public class SuperDemo_1 extends Box public SuperDemo_1(double w,double h,double d) super(w,h,d); 74調用超類(父類)的方法class People protected int
44、age ; protected void show() System.out.println(父類 Show); public class SuperDemo_2 extends People protected void show() System.out.println(子類 Show); public void testShow() this.show(); super.show(); public static void main(String args) SuperDemo_2 s = new SuperDemo_2(); s.testShow(); 75注意的是,this和supe
45、r都是非靜態(tài)的,所以這兩個關鍵字都無法在靜態(tài)方法內部進行使用。76多態(tài)(Polymorphism)Polymorphism源于希臘文,意思是“多種形式”定義:使用父類對象的地方都可以使用子類的對象,這就是所謂的多態(tài)。簡單來說:多態(tài)意味著父類型的變量可以引用子類型的對象。77父類對象與子類對象的轉換 1 子類對象可以視作是一個父類的對象 如: Student對象也是一個People對象 2 父類對象不能被當作一個子類對象 3 如果一個方法的形參是父類對象,調用這個方法時 可以使用子類的對象作為實際參數(shù) 4 如果父類對象指向的實際上確實是一個子類對象,那么這個 父類對象可以用強制類型轉換成子類對象
46、的引用78Polymorphism, Dynamic Binding and Generic Programmingpublic class PolymorphismDemo public static void main(String args) m(new GraduateStudent(); m(new Student(); m(new Person(); m(new Object(); public static void m(Object x) System.out.println(x.toString(); class GraduateStudent extends Student
47、 class Student extends Person public String toString() return Student; class Person extends Object public String toString() return Person; Method m takes a parameter of the Object type. You can invoke it with any object.An object of a subtype can be used wherever its supertype value is required. Thi
48、s feature is known as polymorphism.(多態(tài)的定義)When the method m(Object x) is executed, the argument xs toString method is invoked. x may be an instance of GraduateStudent, Student, Person, or Object. Classes GraduateStudent, Student, Person, and Object have their own implementation of the toString metho
49、d. Which implementation is used will be determined dynamically by the Java Virtual Machine at runtime. This capability is known as dynamic binding. 79Dynamic BindingDynamic binding works as follows: Suppose an object o is an instance of classes C1, C2, ., Cn-1, and Cn, where C1 is a subclass of C2,
50、C2 is a subclass of C3, ., and Cn-1 is a subclass of Cn. That is, Cn is the most general class, and C1 is the most specific class. In Java, Cn is the Object class. If o invokes a method p, the JVM searches the implementation for the method p in C1, C2, ., Cn-1 and Cn, in this order, until it is foun
51、d. Once an implementation is found, the search stops and the first-found implementation is invoked.80Method Matching vs. BindingMatching a method signature and binding a method implementation are two issues. The compiler finds a matching method according to parameter type, number of parameters, and
52、order of the parameters at compilation time. A method may be implemented in several subclasses. The Java Virtual Machine dynamically binds the implementation of the method at runtime. See Review Questions 10.7 and 10.9. 匹配一個方法簽名與綁定方法實現(xiàn)是2個不同的問題:方法匹配:根據(jù)參數(shù)的類型、個數(shù)以及出現(xiàn)的順序來匹配選擇。綁定方法的實現(xiàn):由于一個方法可能被幾個子類實現(xiàn)。所以JV
53、M在運行時動態(tài)綁定方法的實現(xiàn)。81Generic Programming(泛型編程)public class PolymorphismDemo public static void main(String args) m(new GraduateStudent(); m(new Student(); m(new Person(); m(new Object(); public static void m(Object x) System.out.println(x.toString(); class GraduateStudent extends Student class Student e
54、xtends Person public String toString() return Student; class Person extends Object public String toString() return Person; Polymorphism allows methods to be used generically for a wide range of object arguments. This is known as generic programming. If a methods parameter type is a superclass (e.g.,
55、 Object), you may pass an object to this method of any of the parameters subclasses (e.g., Student or String). When an object (e.g., a Student object or a String object) is used in the method, the particular implementation of the method of the object that is invoked (e.g., toString) is determined dy
56、namically.82Casting Objects(轉換對象)You have already used the casting operator to convert variables of one primitive type to another. Casting can also be used to convert an object of one class type to another within an inheritance hierarchy. In the preceding section, the statement m(new Student();assig
57、ns the object new Student() to a parameter of the Object type. This statement is equivalent to:Object o = new Student(); / Implicit casting(隱式轉換)m(o);The statement Object o = new Student(), known as implicit casting, is legal because an instance of Student is automatically an instance of Object.83Wh
58、y Casting Is Necessary?Suppose you want to assign the object reference o to a variable of the Student type using the following statement:Student b = o; /這種做法會產生編譯錯誤A compilation error would occur. Why does the statement Object o = new Student() work and the statement Student b = o doesnt? This is be
59、cause a Student object is always an instance of Object, but an Object is not necessarily an instance of Student. Even though you can see that o is really a Student object, the compiler is not so clever to know it. To tell the compiler that o is a Student object, use an explicit casting. The syntax i
60、s similar to the one used for casting among primitive data types. Enclose the target object type in parentheses and place it before the object to be cast, as follows:Student b = (Student)o; / Explicit casting84Casting fromSuperclass to Subclass從父類對象轉換為子類對象時必須進行顯式強制轉換。而且未必成功。Explicit casting must be
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 上饒衛(wèi)生健康職業(yè)學院《蒙古語標準音訓練》2023-2024學年第一學期期末試卷
- 2025年外貿英語與實務考試試卷及答案
- 山東體育學院《大數(shù)據(jù)平臺技術》2023-2024學年第二學期期末試卷
- 2025年藝術設計與傳媒專業(yè)考試試題及答案
- 江蘇省東臺市第二聯(lián)盟2024-2025學年初三下學期階段測試生物試題試卷含解析
- 寧德市福鼎市2025年三年級數(shù)學第二學期期末學業(yè)質量監(jiān)測模擬試題含解析
- 2025年心理學專業(yè)碩士研究生入學試題及答案
- 晉城職業(yè)技術學院《語言學基礎》2023-2024學年第一學期期末試卷
- 四川省成都市高新南區(qū)2025年第一次教學質量檢測試題(合肥一模)數(shù)學試題含解析
- 四川省南部縣2024-2025學年初三下學期暑假聯(lián)考語文試題含解析
- 2025年儲能項目可行性分析報告
- 2025年北京市海淀區(qū)九年級初三一模英語試卷(含答案)
- 2025年山西焦煤集團國際發(fā)展股份有限公司招聘筆試參考題庫附帶答案詳解
- DB32T 4793-2024球墨鑄鐵管排水系統(tǒng)應用技術規(guī)程
- 八年級音樂上冊校園的早晨省公開課一等獎新課獲獎課件
- 《食品生產經營企業(yè)落實食品安全主體責任監(jiān)督管理規(guī)定》解讀與培訓
- 城市更新與歷史文化保護-全面剖析
- 火災自動報警系統(tǒng)設計規(guī)范完整版2025年
- 2025屆廣東省燕博園聯(lián)考(CAT)高三下學期3月模擬測試物理試題(原卷版+解析版)
- 2025年鐵路小型養(yǎng)路機械市場分析現(xiàn)狀
- 《海參的品種與功效》課件
評論
0/150
提交評論