第五章 對象及類_第1頁
第五章 對象及類_第2頁
第五章 對象及類_第3頁
第五章 對象及類_第4頁
第五章 對象及類_第5頁
已閱讀5頁,還剩29頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領

文檔簡介

第五章對象及類對象與類對象生命周期類的創(chuàng)建重載子類1對象的基本概念面向?qū)ο蟪绦蛘Z言三個關鍵特點:封裝(Encapsulation)多態(tài)(Polymorphism)繼承(Inheritance)2基本數(shù)據(jù)類型和聚集類型的變量與一些操作(如+,-)之間不需特殊的聯(lián)系。在面向?qū)ο笳Z言中,在數(shù)據(jù)類型的聲明與操作這些數(shù)據(jù)的代碼聲明之間建立緊密聯(lián)系,這種聯(lián)系通常描述為一種抽象數(shù)據(jù)類型。在Java中,抽象數(shù)據(jù)類型的概念用類來實現(xiàn)。

抽象數(shù)據(jù)類型3類和對象類是特定類型對象的定義,包括:對象包含的數(shù)據(jù),對象的創(chuàng)建及對象對自身數(shù)據(jù)操作的方法。類是一個模板。對象是在其類模型基礎上構(gòu)造出的,是具體的實例。4類和對象舉例類定義:ClassEmpInfo{ Stringname; Stringdesignation; Stringdepartment; voidprint(){System.out.println(name+“is”+ designation+“at”+department);} }對象的生成與使用:…

EmpInfoemployee=newEmpInfo(); =“RobertJavaman”; employee.designation=“Manager”; employee.department=“Coffeeshop”; employee.print();...5創(chuàng)建對象例:Pointorigin_one;origin_one=newPoint(23,94);Rectanglerect_one=newRectangle(origin_one,100,200);Rectanglerect_two=newRectangle(50,100);創(chuàng)建對象的三個步驟:

聲明(Declaration)

實例化(Instantiation)

初始化(Initialization)6對象的實例化使用new操作符進行對象的實例化,為對象分配空間,并返回指向該對象的引用。格式:new對象所屬類的構(gòu)造函數(shù)

類的構(gòu)造函數(shù)負責對新創(chuàng)建的對象進行初始化7對象實例化過程構(gòu)造與初始化對象的過程(調(diào)用newXxxx()):

開辟內(nèi)存空間及類成員變量的初始化: 數(shù)值型:0;布爾型:false;

引用型:null;字符串型:null;

顯式初始化:執(zhí)行類成員聲明時帶有的簡單賦值表達式。

publicclassInitialized{ privateintx=5; privateStringname=“Fred”; … }

執(zhí)行構(gòu)造函數(shù)。8對象的回收垃圾收集機制(garbagecollection):Java運行環(huán)境當確定某個對象不再被使用時,將其刪除。一個對象在沒有引用指向它時,可作為垃圾收集。垃圾搜集器:Java運行環(huán)境中的垃圾搜集器周期性地釋放 不用對象占用的空間。9垃圾收集機制C++:A*a=newA(); A*b=a; A*c=a;Java:Aa=newA(); Ab=a; Ac=a;ab

c

b

c(指針懸空)ab

c

b

c//a使用完,將其刪除

deletea;//a使用完,將其刪除

a=null;10類的創(chuàng)建

11構(gòu)造方法定義:public

類名(參數(shù)){…}注意:方法名必須與類名相同。不能帶返回類型。類的構(gòu)造函數(shù)12如果在類定義中無構(gòu)造函數(shù),Java在編譯時可缺省加入構(gòu)造方法。如publicEmployee(){};一旦在類中有一個自己聲明的構(gòu)造函數(shù),則缺省的構(gòu)造函數(shù)將不被加到源程序中。缺省構(gòu)造函數(shù)13類成員方法定義一般格式:<modifiers><return_type><name>([<argument_list>])[throws<exception>]{<block>}

方法是傳值的,方法調(diào)用不會改變參數(shù)的值。當對象作為參數(shù)時,參數(shù)的值是該對象的引用,這時對象的內(nèi)容可以在方法中改變,但是對象的引用不會改變。14舉例PublicclassPassTest{ floatptValue; publicvoidchangeInt(intvalue){ value=55;} publicvoidchangeStr(Stringvalue){ value=newString(“different”);} publicvoidchangeObjValue(PassTestref){ ref.ptValue=99.0f;} publicstaticvoidmain(Stringargs[]){ Stringstr; intval;

PassTestpt=newPassTest();

val=11; pt.changeInt(val); System.out.println(“Intvalueis:”+val);

str=newString(“hello”); pt.changeStr(str); System.out.println(“strvalueis:”+str); pt.ptvalue=101.0f; pt.changeObjValue(pt); System.out.println(“ptvalueis:”+pt.ptValue); }} 結(jié)果:

IntValueis:11StrValueis:helloptvalueis:99.0f15數(shù)據(jù)隱藏與封裝數(shù)據(jù)隱藏:使用private定義的成員變量,只能在成員方法中使用,其它方法中禁止使用。優(yōu)點:保證對象中數(shù)據(jù)的一致性。封裝:基本數(shù)據(jù)和對數(shù)據(jù)進行的操作方法的結(jié)合。

優(yōu)點:隱藏類中具體實現(xiàn)的細節(jié)。強迫程序員使用統(tǒng)一的接口訪問數(shù)據(jù)。使代碼可維護性好。16數(shù)據(jù)隱藏與封裝舉例ClassDate{ privateintday,month,year; voidsetDate(inta,intb,intc){ day=a; month=b; year=c; } }…Dated1;d1.newDate();d1.setDate(30,9,2001);...d1.day=30;(錯誤!)17“this“引用關鍵字this用來指向當前對象本身。例:classDate{ privateintday,month,year; publicDategetTommorrow(){ this.day++; … }18重載(Overloading)含義:在同一個類中一個方法名被用來定義多個方法。

classScreen{ publicvoidprint(inti){…} publicvoidprint(floati){…} publicvoidprint(Stringstr){…} }重載必須遵守原則:參數(shù)表必須不同,以此區(qū)分不同方法體。返回類型、修飾符可相同或不相同。19激活重載的構(gòu)造函數(shù)在一個構(gòu)造函數(shù)中可以利用另一個構(gòu)造函數(shù)。classEmployee{ privateStringname; privateintsalary; publicEmployee(Stringn,ints){ name=n; salary=s; } publicEmployee(Stringn){this(n,0);} publicEmployee(){this(“Unknown”);} }20子類子類表示類之間一種“屬于”(

isa)關系。例:publicclassEmployee{ Stringname; DatehireDate; DatedateofBirth; StringjobTitle; intgrade; … }publicclassManager{ Stringname; DatehireDate; DatedateofBirth; StringjobTitle; intgrade;

Stringdepartment;

Employee[]subordinates; … }21

Java中用extends關鍵字定義子類。Extends關鍵字publicclassEmployee{ Stringname; DatehireDate; DatedateofBirth; StringjobTitle; intgrade; … }publicclassManagerextendsEmployee

{

Stringdepartment;

Employee[]subordinates; }子類是從已有的類創(chuàng)建新類的一種方法。22子類子類繼承父類的屬性、功能(方法),子類中只需聲明特有的東西。帶private修飾符的屬性、方法是不能被繼承的。構(gòu)造函數(shù)不能被繼承。在方法中調(diào)用構(gòu)造方法用this()。調(diào)用父類的構(gòu)造方法用super()。 --super指向該關鍵字所在類的父類。23構(gòu)造不同類型數(shù)據(jù)的集合

Java中允許構(gòu)造如下類型的數(shù)組:

Employee[]staff=newEmployee[1024]; staff[0]=newManager(); staff[1]=newWorker(); staff[2]=newEmployee(); …----staff是由多種類型的對象組成的。

Java中任何一個子類的實例都可作為父類的實例使用,可以調(diào)用父類具有的方法。24單繼承

Java是單繼承的,即只能從一個類繼承,

extends后類名只能有一個。單繼承的優(yōu)點:代碼更可靠可以用接口彌補

用一個類實現(xiàn)多個接口,達到多繼承效果。25多態(tài)Java允許父類對象的變量作為子類對象的變量使用。但通過該變量(如e)只能訪問父類的方法,子類特有的部分被隱藏。如:Employeee=newManager();多態(tài)含義:

Anobjecthasonlyoneform,whileavariableispolymorphism,sinceitcanrefertoobjectsofdifferentforms,polymorphismistheabilitytohavemanydifferentforms.26Super關鍵字Super指向該關鍵字所在類的父類。PublicclassEmpolyee{ privateStringname; privateintsalary; publicStringgetDetails(){ return“Name:”+name+“\nSalary:”+salary; } }publicclassManagerextendsEmpolyee{ privateStringdepartment; publicStringgetDetails(){ returnsuper.getDetailes()+‘\nDepartment:“+ department; } }27“instanceof”及類型強制轉(zhuǎn)換

Instanceof

測試對象類型

Empolyeea=newManager();

ainstanceofManager為true;類型轉(zhuǎn)換父類弱、子類強,指向父類的引用不能直接按子類引用,必須要強制類型轉(zhuǎn)換后才能作為子類的引用使用。例:publicvoidmethod(Employeee){ if(einstanceofManager){ managerm=(manager)e; m.department=“…”; … }}28重寫(Overridingmethods)子類可以改變從父類繼承的行為。被重寫方法的返回值、方法名、參數(shù)列表要與父類中的方法完全一樣。運行時確定使用父類還是子類的方法。

Employeee=newManager();e.getDetails();29Overriding示例publicclassStack{privateVectoritems;//codeforStack'smethodsandconstructornotshown//overridesObject'stoStringmethod

publicStringtoString(){intn=items.size();StringBufferresult=newStringBuffer();result.

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論