java 第十章.ppt_第1頁
java 第十章.ppt_第2頁
java 第十章.ppt_第3頁
java 第十章.ppt_第4頁
java 第十章.ppt_第5頁
已閱讀5頁,還剩48頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡介

1 第十章抽象類和接口 2 第一個(gè)話題 抽象類 在類的繼承層次中 子類越來越具體 而父類更加一般化和抽象 類設(shè)計(jì)過程中應(yīng)使父類包含子類的一般特征 有時(shí)父類太抽象而不能有一個(gè)具體的實(shí)例 稱為抽象類 3 TheabstractModifier Theabstractclass不能被實(shí)例化在子類中擴(kuò)展和實(shí)現(xiàn)Theabstractmethod方法的標(biāo)識(shí) 無須實(shí)現(xiàn) 4 一個(gè)實(shí)例 5 AbstractClasses GeometricObject Circle Rectangle 6 注意 非抽象類不能包含抽象方法 如果一個(gè)抽象父類的子類不能實(shí)現(xiàn)所有的抽象方法 它必須聲明為抽象的 一個(gè)由抽象類擴(kuò)展出來的非抽象類中 所有的方法都必須實(shí)現(xiàn) 7 注意 抽象類不能用new實(shí)例化 但可以定義它的構(gòu)造方法 這種構(gòu)造方法將在它的子類構(gòu)造方法中調(diào)用 GeometricObject的構(gòu)造方法在Circleclass和Rectangleclass中調(diào)用 8 注意 包含抽象方法的類必須是抽象的 但是 允許聲明沒有抽象方法的抽象類 這樣 不能使用new操作符創(chuàng)建類的實(shí)例 9 NOTE 子類可以聲明為抽象的 即使它的父類是具體的 例如 Object類是具體的 當(dāng)時(shí)它的子類GeometricObject是抽象的 10 NOTE 子類可以覆蓋它的父類的方法 并將其聲明為abstract 11 NOTE 不能用new操作符創(chuàng)建抽象類的實(shí)例 但是 抽象類可以用作數(shù)據(jù)類型 GeometricObject geo newGeometricObject 10 12 使用抽象類 使用GeometricObject類創(chuàng)建2個(gè)幾何對(duì)象 一個(gè)圓和一個(gè)矩形 調(diào)用equalArea方法檢查兩個(gè)對(duì)象面積是否相等 調(diào)用displayGeometricObject方法顯示2個(gè)對(duì)象 TestGeometricObject Run 13 請(qǐng)大家思考一下 如果GeometricObject里面沒有定義getArea和getPerimeter方法 就不能再該程序中定義equalArea和displayObject方法 可見在GeometricObject中定義抽象方法的好處 多態(tài) 動(dòng)態(tài)綁定 14 第二個(gè)話題 接口 接口是一種類似類的結(jié)構(gòu) 某種意義上是一種特殊的抽象類 這種抽象類中只包含常量和方法的定義 而沒有方法的實(shí)現(xiàn) 普通的抽象類可包含變量和具體的方法 publicinterfaceInterfaceName constantdeclarations methodsignatures 15 接口是特殊的類 接口編譯的結(jié)果是一個(gè)單獨(dú)的字節(jié)碼文件 與抽象類一樣 不能使用new創(chuàng)建接口的實(shí)例 和使用抽象類類似 16 接口定義實(shí)例 假定要設(shè)計(jì)一個(gè)求兩個(gè)對(duì)象中較大的一般方法 對(duì)象可以是學(xué)生 圓形或舉行 可以這樣定義接口 Thisinterfaceisdefinedin java langpackagepackagejava lang publicinterfaceComparable publicintcompareTo Objecto 在接口中如果不寫public 則也是public訪問權(quán)限 17 StringandDateClasses 在Java庫中很多類 e g StringandDate 都實(shí)現(xiàn)了Comparable接口用于比較對(duì)象 newString instanceofStringnewString instanceofComparablenewjava util Date instanceofjava util Datenewjava util Date instanceofComparable 18 一般max方法 返回值是Comparable類型 你必須將其顯示轉(zhuǎn)換為相應(yīng)的類型StringorDate 若參數(shù)不是Comparable的實(shí)例 編譯時(shí)出錯(cuò) 若參數(shù)不是Comparable的實(shí)例 運(yùn)行時(shí)出錯(cuò) 19 聲明類以實(shí)現(xiàn)Comparable接口 用max方法不能比較Rectangle 因?yàn)镽ectangle沒有實(shí)現(xiàn)Comparable 不過可以聲明一個(gè)新的rectangle類 這個(gè)類實(shí)現(xiàn)了Comparable 將其命名為ComparableRectangle ComparableRectangle ComparableRectanglerectangle1 newComparableRectangle 4 5 ComparableRectanglerectangle2 newComparableRectangle 3 6 System out println Max max rectangle1 rectangle2 Object類中沒有定義compareTo方法 20 接口和抽象類的比較 接口中 數(shù)據(jù)一定是常量 抽象類中可以有各種類型的數(shù)據(jù) 接口的方法只有標(biāo)識(shí) 抽象類中可以有具體的方法 21 接口和抽象類的比較 Alldatafieldsarepublicfinalstaticandallmethodsarepublicabstractinaninterface 鑒于以上原因 接口中的一些修飾符可以省略 接口中定義的常量 可以這樣訪問 InterfaceName CONSTANT NAME 22 接口的繼承和派生 所有的類共享一個(gè)根Obje類 當(dāng)接口沒有共同的根 一下是接口的繼承關(guān)系 23 一個(gè)繼承的寫法 publicclassNewClassextendsBaseClassimplementsInterface1 Interface2 InterfaceN publicinterfaceNewInterextendsInterf1 Interf2 InterfN 有些時(shí)候需要子類繼承幾個(gè)父類 即多重繼承 而Java不支持多重繼承 每個(gè)子類至多一個(gè)直接的父類 使用接口可以實(shí)現(xiàn)多重繼承的效果 強(qiáng)是弱是 24 創(chuàng)建自定義接口 publicinterfaceEdible Describehowtoeat publicStringhowToEat classAnimal classChickenextendsAnimalimplementsEdible publicStringhowToEat return Fryit classTigerextendsAnimal classabstractFruitimplementsEdible classAppleextendsFruit publicStringhowToEat return Makeapplecider classOrangeextendsFruit publicStringhowToEat return Makeorangejuice 25 classChickenextendsAnimalimplementsEdible Comparable intweight publicChicken intweight this weight weight publicStringhowToEat return Fryit publicintcompareTo Objecto returnweight Chicken o weight 實(shí)現(xiàn)多接口 修改上一頁的Chicken類 26 包裝類 WrapperClasses BooleanCharacterShortByte IntegerLongFloatDouble NOTE 1 Thewrapperclassesdonothaveno argconstructors 2 Theinstancesofallwrapperclassesareimmutable i e theirinternalvaluescannotbechangedoncetheobjectsarecreated 27 基本數(shù)據(jù)類型處理為對(duì)象 把基本類型包裝成對(duì)象 對(duì)應(yīng)的類稱為包裝類 使用包裝對(duì)象代替基本類型變量 可以進(jìn)行通用程序設(shè)計(jì) Java提供的包裝類包括 Boolean Character Double Float Byte Short Integer Long 28 Number類及子類 Number類抽象轉(zhuǎn)換方法publicbytebyteValue publicshortshortValue publicintintValue publiclonglongValue publicfloatfloatValue doubledoubledoubleValue 每個(gè)包裝類覆蓋了方法toString equals hashCode 實(shí)現(xiàn)了接口Comparable 29 Number類及子類 數(shù)值包裝類的構(gòu)造方法publicInteger intvalue publicInteger Strings publicDouble doublevalue publicDouble Strings 例 DoubledoubleObject newDouble 5 DoubledoubleObject newDouble 5 IntergerintObject newInteger 5 IntergerintObject newInteger 5 注意 沒有無參的構(gòu)造方法 包裝類的實(shí)例是不可變的 30 Number類及子類 Number類的常量 MAX VALUE MIN VALUE對(duì)Byte Short Integer Long分別表示給類型的最大值和最小值 對(duì)Float和Double分別表示類型的最大值和最小正值 31 Number類及子類 類型轉(zhuǎn)換 每個(gè)數(shù)值包裝類都實(shí)現(xiàn)了Number類中的抽象方法doubleValue floatValue intValue longValue shortValue 并覆蓋了Object的toString和equals方法 例 longl doubleObject longValue inti integerObject intValue doubled 5 9 DoubledoubleObject newDouble d Strings doubleObject toString 32 Number類及子類 static方法 ValueOf Strings 創(chuàng)建一個(gè)新的對(duì)象 并初始化為該字符串表示的值 每個(gè)數(shù)值類分別提供了把字符形式轉(zhuǎn)換成數(shù)字的方法 parseByte parseShort parseInt 和parseLong parseFloat parseDouble 這些方法返回與調(diào)用它們的數(shù)值字符串相應(yīng)的字節(jié) byte 短整型 short 整型 int 和長整型 long 值publicstaticintparseInt Strings intradix 指明了基數(shù)是radix的轉(zhuǎn)換 publicstaticintparseInt Strings 基數(shù)是10publicstaticdoubleparseDouble Strings 33 例Integer parseInt 11 2 Integer parseInt 12 8 Integer parseInt 13 10 Integer parseInt 1A 16 小結(jié)數(shù)值包裝類的方法 構(gòu)造方法 Value valueOf parse 34 例2對(duì)象數(shù)組排序 編程實(shí)現(xiàn)可比較的對(duì)象的數(shù)組排序 對(duì)象是接口Comparable的實(shí)例 使用方法compareTo進(jìn)行比較 可以用于所有實(shí)現(xiàn)了接口Comparable的類型對(duì)象的比較 GenericSort java 注意 若A是B的子類 則A 的實(shí)例亦是B 的實(shí)例 類型轉(zhuǎn)換時(shí) int可賦值給double類型 但是int 與double 是不兼容的類型 35 ThetoString equals andhashCodeMethods EachwrapperclassoverridesthetoString equals andhashCodemethodsdefinedintheObjectclass SinceallthenumericwrapperclassesandtheCharacterclassimplementtheComparableinterface thecompareTomethodisimplementedintheseclasses 36 TheNumberClass EachnumericwrapperclassextendstheabstractNumberclass whichcontainsthemethodsdoubleValue floatValue intValue longValue shortValue andbyteValue Thesemethods convert objectsintoprimitivetypevalues ThemethodsdoubleValue floatValue intValue longValueareabstract ThemethodsbyteValueandshortValuearenotabstract whichsimplyreturn byte intValue and short intValue respectively 37 TheIntegerandDoubleClasses 38 TheIntegerClassandtheDoubleClass ConstructorsClassConstantsMAX VALUE MIN VALUEConversionMethods 39 NumericWrapperClassConstructors Youcanconstructawrapperobjecteitherfromaprimitivedatatypevalueorfromastringrepresentingthenumericvalue TheconstructorsforIntegerandDoubleare publicInteger intvalue publicInteger Strings publicDouble doublevalue publicDouble Strings 40 NumericWrapperClassConstants EachnumericalwrapperclasshastheconstantsMAX VALUEandMIN VALUE MAX VALUErepresentsthemaximumvalueofthecorrespondingprimitivedatatype ForByte Short Integer andLong MIN VALUErepresentstheminimumbyte short int andlongvalues ForFloatandDouble MIN VALUErepresentstheminimumpositivefloatanddoublevalues Thefollowingstatementsdisplaythemaximuminteger 2 147 483 647 theminimumpositivefloat 1 4E 45 andthemaximumdoublefloating pointnumber 1 79769313486231570e 308d 41 ConversionMethods EachnumericwrapperclassimplementstheabstractmethodsdoubleValue floatValue intValue longValue andshortValue whicharedefinedintheNumberclass Thesemethods convert objectsintoprimitivetypevalues 42 TheStaticvalueOfMethods Thenumericwrapperclasseshaveausefulclassmethod valueOf Strings Thismethodcreatesanewobjectinitializedtothevaluerepresentedbythespecifiedstring Forexample DoubledoubleObject Double valueOf 12 4 IntegerintegerObject Integer valueOf 12 43 TheMethodsforParsingStringsintoNumbers YouhaveusedtheparseIntmethodintheIntegerclasstoparseanumericstringintoanintvalueandtheparseDoublemethodintheDoubleclasstoparseanumericstringintoadoublevalue Eachnumericwrapperclasshastwooverloadedparsingmethodstoparseanumericstringintoanappropriatenumericvalue 44 Example SortinganArrayofObjects Objective Theexamplepresentsagenericmethodforsortinganarrayofobjects TheobjectsareinstancesoftheComparableinterfaceandtheyarecomparedusingthecompareTomethod GenericSort Run 45 TIP JavaprovidesastaticsortmethodforsortinganarrayofObjectinthejava util Arraysclass Soyoucanusethefollowingcodetosortarraysinthisexample java util Arrays sort intArray java util Arrays sort doubleArray java util Arrays sort charArray java util Arrays sort stringArray 46 NOTE Arraysareobjects AnarrayisaninstanceoftheObjectclass Furthermore ifAisasubclassofB everyinstanceofA isaninstanceofB Therefore thefollowingstatementsarealltrue newint 10 instanceofObjectnewGregorianCalendar 10 instanceofCalendar newCalendar 10 instanceofObject newCalendar 10 instanceofObject 47 CAUTION Althoughanintvaluecanbeassignedtoadoubletypevariable int anddouble aretwoincompatibletypes Therefore youcannotassignanint arraytoavariableofdouble orObject type 48 AutomaticConversionBetweenPrimitiveTypesandWrapperClassTypes JDK1 5allowsprimitivetypeandwrapperclassestobeconvertedautomatically Forexample thefollowingstatementin a canbesimplifiedasin b JDK1 5Feature Integer intArray 1 2 3 System out println intArray 0 intArray 1 intArray 2 Unboxing 49 NOTEtoInstructor Optionalpath YoumaycoverChapter14 Event DrivenProgramming orChapter21 Generics now 50 HandlingGUIEvents Sourceobject e g button Listenerobjectcontainsamethodforprocessingtheevent HandleEvent Run OptionalGUI 51 TraceExecution publicclassHandleEventextendsJFrame publicHandleEvent OKListenerCl

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(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ì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論