java 第十章.ppt_第1页
java 第十章.ppt_第2页
java 第十章.ppt_第3页
java 第十章.ppt_第4页
java 第十章.ppt_第5页
已阅读5页,还剩48页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1 第十章抽象类和接口 2 第一个话题 抽象类 在类的继承层次中 子类越来越具体 而父类更加一般化和抽象 类设计过程中应使父类包含子类的一般特征 有时父类太抽象而不能有一个具体的实例 称为抽象类 3 TheabstractModifier Theabstractclass不能被实例化在子类中扩展和实现Theabstractmethod方法的标识 无须实现 4 一个实例 5 AbstractClasses GeometricObject Circle Rectangle 6 注意 非抽象类不能包含抽象方法 如果一个抽象父类的子类不能实现所有的抽象方法 它必须声明为抽象的 一个由抽象类扩展出来的非抽象类中 所有的方法都必须实现 7 注意 抽象类不能用new实例化 但可以定义它的构造方法 这种构造方法将在它的子类构造方法中调用 GeometricObject的构造方法在Circleclass和Rectangleclass中调用 8 注意 包含抽象方法的类必须是抽象的 但是 允许声明没有抽象方法的抽象类 这样 不能使用new操作符创建类的实例 9 NOTE 子类可以声明为抽象的 即使它的父类是具体的 例如 Object类是具体的 当时它的子类GeometricObject是抽象的 10 NOTE 子类可以覆盖它的父类的方法 并将其声明为abstract 11 NOTE 不能用new操作符创建抽象类的实例 但是 抽象类可以用作数据类型 GeometricObject geo newGeometricObject 10 12 使用抽象类 使用GeometricObject类创建2个几何对象 一个圆和一个矩形 调用equalArea方法检查两个对象面积是否相等 调用displayGeometricObject方法显示2个对象 TestGeometricObject Run 13 请大家思考一下 如果GeometricObject里面没有定义getArea和getPerimeter方法 就不能再该程序中定义equalArea和displayObject方法 可见在GeometricObject中定义抽象方法的好处 多态 动态绑定 14 第二个话题 接口 接口是一种类似类的结构 某种意义上是一种特殊的抽象类 这种抽象类中只包含常量和方法的定义 而没有方法的实现 普通的抽象类可包含变量和具体的方法 publicinterfaceInterfaceName constantdeclarations methodsignatures 15 接口是特殊的类 接口编译的结果是一个单独的字节码文件 与抽象类一样 不能使用new创建接口的实例 和使用抽象类类似 16 接口定义实例 假定要设计一个求两个对象中较大的一般方法 对象可以是学生 圆形或举行 可以这样定义接口 Thisinterfaceisdefinedin java langpackagepackagejava lang publicinterfaceComparable publicintcompareTo Objecto 在接口中如果不写public 则也是public访问权限 17 StringandDateClasses 在Java库中很多类 e g StringandDate 都实现了Comparable接口用于比较对象 newString instanceofStringnewString instanceofComparablenewjava util Date instanceofjava util Datenewjava util Date instanceofComparable 18 一般max方法 返回值是Comparable类型 你必须将其显示转换为相应的类型StringorDate 若参数不是Comparable的实例 编译时出错 若参数不是Comparable的实例 运行时出错 19 声明类以实现Comparable接口 用max方法不能比较Rectangle 因为Rectangle没有实现Comparable 不过可以声明一个新的rectangle类 这个类实现了Comparable 将其命名为ComparableRectangle ComparableRectangle ComparableRectanglerectangle1 newComparableRectangle 4 5 ComparableRectanglerectangle2 newComparableRectangle 3 6 System out println Max max rectangle1 rectangle2 Object类中没有定义compareTo方法 20 接口和抽象类的比较 接口中 数据一定是常量 抽象类中可以有各种类型的数据 接口的方法只有标识 抽象类中可以有具体的方法 21 接口和抽象类的比较 Alldatafieldsarepublicfinalstaticandallmethodsarepublicabstractinaninterface 鉴于以上原因 接口中的一些修饰符可以省略 接口中定义的常量 可以这样访问 InterfaceName CONSTANT NAME 22 接口的继承和派生 所有的类共享一个根Obje类 当接口没有共同的根 一下是接口的继承关系 23 一个继承的写法 publicclassNewClassextendsBaseClassimplementsInterface1 Interface2 InterfaceN publicinterfaceNewInterextendsInterf1 Interf2 InterfN 有些时候需要子类继承几个父类 即多重继承 而Java不支持多重继承 每个子类至多一个直接的父类 使用接口可以实现多重继承的效果 强是弱是 24 创建自定义接口 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 实现多接口 修改上一页的Chicken类 26 包装类 WrapperClasses BooleanCharacterShortByte IntegerLongFloatDouble NOTE 1 Thewrapperclassesdonothaveno argconstructors 2 Theinstancesofallwrapperclassesareimmutable i e theirinternalvaluescannotbechangedoncetheobjectsarecreated 27 基本数据类型处理为对象 把基本类型包装成对象 对应的类称为包装类 使用包装对象代替基本类型变量 可以进行通用程序设计 Java提供的包装类包括 Boolean Character Double Float Byte Short Integer Long 28 Number类及子类 Number类抽象转换方法publicbytebyteValue publicshortshortValue publicintintValue publiclonglongValue publicfloatfloatValue doubledoubledoubleValue 每个包装类覆盖了方法toString equals hashCode 实现了接口Comparable 29 Number类及子类 数值包装类的构造方法publicInteger intvalue publicInteger Strings publicDouble doublevalue publicDouble Strings 例 DoubledoubleObject newDouble 5 DoubledoubleObject newDouble 5 IntergerintObject newInteger 5 IntergerintObject newInteger 5 注意 没有无参的构造方法 包装类的实例是不可变的 30 Number类及子类 Number类的常量 MAX VALUE MIN VALUE对Byte Short Integer Long分别表示给类型的最大值和最小值 对Float和Double分别表示类型的最大值和最小正值 31 Number类及子类 类型转换 每个数值包装类都实现了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 创建一个新的对象 并初始化为该字符串表示的值 每个数值类分别提供了把字符形式转换成数字的方法 parseByte parseShort parseInt 和parseLong parseFloat parseDouble 这些方法返回与调用它们的数值字符串相应的字节 byte 短整型 short 整型 int 和长整型 long 值publicstaticintparseInt Strings intradix 指明了基数是radix的转换 publicstaticintparseInt Strings 基数是10publicstaticdoubleparseDouble Strings 33 例Integer parseInt 11 2 Integer parseInt 12 8 Integer parseInt 13 10 Integer parseInt 1A 16 小结数值包装类的方法 构造方法 Value valueOf parse 34 例2对象数组排序 编程实现可比较的对象的数组排序 对象是接口Comparable的实例 使用方法compareTo进行比较 可以用于所有实现了接口Comparable的类型对象的比较 GenericSort java 注意 若A是B的子类 则A 的实例亦是B 的实例 类型转换时 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等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论