《第6讲面向对象特征解析课件.ppt》由会员分享,可在线阅读,更多相关《第6讲面向对象特征解析课件.ppt(36页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、第第6讲:面向对象特征讲:面向对象特征总结与实例总结与实例vv1接口与抽象类接口与抽象类vv2异常类异常类vv3类与类型类与类型vv4基础数据结构基础数据结构1接口与抽象类接口与抽象类1.1接口语法接口语法public interface 接口名 extends 父接口名列表/接口体;/常量域声明 public static final 域类型 域名=常量值;/抽象方法声明 public abstract native返回值 方法名(参数列表)throw异常列表;从上面的语法规定可以看出,定义接口与定义类非常相似,实际上完全可以把接口理解成为一种特殊的类,接口是由常量和抽象方法组成的特殊类。1
2、.2接口声明接口声明(1)接口中的属性都是用 final修饰的常量,在这个类中,所有的成员函数都是抽象的,也就是说它们都只有说明没有定义;(2)接口中的方法都是用abstract修饰的抽象方法,在接口中只能给出这些抽象方法的方法名、返回值和参数列表,而不能定义方法体,即仅仅规定了一组信息交换、传输和处理的“接口”。1.3接口实现接口实现在类的声明部分,用implements关键字声明该类将要实现哪些接口如果实现某接口的类不是abstract的抽象类,则在类的定义部分必须实现指定接口的所有抽象方法,即为所有抽象方法定义方法体,而且方法头部分应该与接口中的定义完全一致,即有完全相同的返回值和参数列
3、表如果实现某接口的类是abstract的抽象类,则它可以不实现该接口所有的方法一个类在实现某接口的抽象方法时,必须使用完全相同的方法头接口的抽象方法,其访问限制符都已指定是public,所以类在实现方法时,必须显式地使用public修饰符2异常类异常类vv异常:正常程序所不能处理或者无法异常:正常程序所不能处理或者无法处理的情况。处理的情况。原因:原因:1、避免程序繁琐与复杂、避免程序繁琐与复杂2、当前层次处理不恰当、当前层次处理不恰当引入异常机制的目的:引入异常机制的目的:1、使异常处理简化、统一、使异常处理简化、统一2、保留异常处理的灵活性、保留异常处理的灵活性2.1异常异常类类vv通常用
4、类通常用类Exception及其子类来描述异常的及其子类来描述异常的特征。特征。按照编译时是否能够监测,分为按照编译时是否能够监测,分为:CheckedExceptionUncheckedException两种,其中非监测异两种,其中非监测异常又分为常又分为RuntimeException、Error。通常。通常Error是致命性的,无法由程序来处理是致命性的,无法由程序来处理,例如例如VirtualMachineError.自定义异常类本例中,当a的值小于10或大于100时,将产生异常。class MyException1 extends Exceptionint num;MyExcepti
5、on1(int a)num=a;public String toString()return num+100!rn值必须小于100;2.2异常产生与声明异常产生与声明声明抛出异常是一个子句,只能加在方法头部的后边。语法格式如下:throws 如:public int read()throws IOException .真正抛出异常的动作是由抛出异常语句来完成的。格式如下:throw ;其中:必须是Throwable类或其子类的对象。如:throw new Exception(这是一个异常);下面的语句在编译时将会产生语法错误:throw new String(能抛出吗?);这是因为String
6、类不是Throwable类的子类。2.2异常产生与声明异常产生与声明从键盘读入汉字,打印出其机内码。注意不是UNICODE码。若按了a键,则立即抛出异常。import java.io.*;public class Ex_Exception3 public static void main(String args)int c;try while(c=System.in.read()!=-1)if(c=a)throw new Exception(键a坏了!);System.out.println(c);catch(IOException e)System.out.println(e);catch(
7、Exception e)System.out.println(e);2.3异常捕获与处理异常捕获与处理Java中使用try-catch-finally语句来捕获并处理异常,try-catch-finally语句的语法格式如下:try/可能会产生异常的程序代码catch(Exception_1 e1)/处理异常Exception_1的代码 catch(Exception_2 e2)/处理异常Exception_2的代码 .catch(Exception_n en)/处理异常Exception_n的代码 finally/通常是释放资源的程序代码 整个语句由try块、catch块和可以缺省final
8、ly块三部分组成。2.3异常捕获与处理异常捕获与处理当产生异常时,程序从上往下依次判该异常是不是catch(Exception_x e)块中Exception_x类或其子类的对象。try-catch-finally语句的嵌套。try-catch-finally语句的try块、catch块、finally块中的程序代码都可以嵌套另外的try-catch-finally语句,且嵌套层次数任意。2.4异常处理总结异常处理总结对Error类或其子类的对象,程序中不必进行处理对RuntimeException类或其子类,程序中可以不必进行处理除此之外的异常,程序员都应该在程序中进行处理。要么用try-c
9、atch-finally进行捕获处理,要么明确表示不处理从而声明抛出异常,要么先捕获处理然后再次抛出。Java的异常处理机制(try-catch-finally语句、throws 子句、throw 语句)带来Java程序代码结构上的改变不能滥用异常机制。简单的出错判断建议用if语句不要过分细分异常3类与类型类与类型vv类经过编译后是二进制的类经过编译后是二进制的class文件,文件,在程序运行时被装入。在程序运行时被装入。vvJava的类是动态装入的。的类是动态装入的。vvClass类封装了关于类的系列操作类封装了关于类的系列操作3.1Class类类vv每个类或者接口都由一个每个类或者接口都由
10、一个Class对象来管理对象来管理vvObject类中的方法类中的方法getClass()()vvpublic final public final public final public final ClassClassClassClass getClassgetClassgetClassgetClass()()()()vvReturnstheruntimeclassofanobject.ThatClassReturnstheruntimeclassofanobject.ThatClassobjectistheobjectthatislockedbystaticobjectistheobje
11、ctthatislockedbystaticsynchronizedmethodsoftherepresentedclass.synchronizedmethodsoftherepresentedclass.vvReturns:Returns:vvtheobjectoftypetheobjectoftypeClassClassClassClassthatrepresentstheruntimethatrepresentstheruntimeclassoftheobject.classoftheobject.vvjava.langClassClassvvjava.lang.Objectjava.
12、lang.Object java.lang.Classjava.lang.Class vvAllImplementedInterfaces:vvSerializablevvfromF:J2SEdocsapijavalangClass.htmlfromF:J2SEdocsapijavalangClass.htmlvvpublicfinalclasspublicfinalclassClassClass vvextendsextendsObjectObject vvimplementsimplementsSerializableSerializablevvInstancesoftheclassIns
13、tancesoftheclassClassClassClassClassrepresentclassesandinterfacesinarunningJavarepresentclassesandinterfacesinarunningJavaapplication.Everyarrayalsobelongstoaclassthatisreflectedasaapplication.EveryarrayalsobelongstoaclassthatisreflectedasaClassClassClassClassobjectobjectthatissharedbyallarrayswitht
14、hesameelementtypeandnumberofdimensions.thatissharedbyallarrayswiththesameelementtypeandnumberofdimensions.TheprimitiveJavatypes(TheprimitiveJavatypes(booleanbooleanbooleanboolean,bytebytebytebyte,charcharcharchar,shortshortshortshort,intintintint,longlonglonglong,floatfloatfloatfloat,and,anddoubledo
15、ubledoubledouble),),andthekeywordandthekeywordvoidvoidvoidvoidarealsorepresentedasarealsorepresentedasClassClassClassClassobjects.objects.vvClassClassClassClasshasnopublicconstructor.Insteadhasnopublicconstructor.InsteadClassClassClassClassobjectsareconstructedobjectsareconstructedautomaticallybythe
16、JavaVirtualMachineasclassesareloadedandbycallstotheautomaticallybytheJavaVirtualMachineasclassesareloadedandbycallstothedefineClassdefineClassdefineClassdefineClassmethodintheclassloader.methodintheclassloader.vvThefollowingexampleusesaThefollowingexampleusesaClassClassClassClassobjecttoprinttheclas
17、snameofanobject:objecttoprinttheclassnameofanobject:vvvoid void void void printClassName(ObjectprintClassName(ObjectprintClassName(ObjectprintClassName(Object objobjobjobj)System.out.println(TheSystem.out.println(TheSystem.out.println(TheSystem.out.println(The class of +class of +class of +class of
18、+objobjobjobj+is +is +is +is +obj.getClass().getNameobj.getClass().getNameobj.getClass().getNameobj.getClass().getName();();();();ItisalsopossibletogettheItisalsopossibletogettheClassClassClassClassobjectforaobjectforanamedtype(orforvoid)usingaclassliteral(JLSSectionnamedtype(orforvoid)usingaclassli
19、teral(JLSSection15.8.215.8.2).Forexample:).Forexample:vvSystem.out.println(TheSystem.out.println(TheSystem.out.println(TheSystem.out.println(The name of class name of class name of class name of class FooFooFooFoo is:+is:+is:+is:+Foo.class.getNameFoo.class.getNameFoo.class.getNameFoo.class.getName()
20、;();();();vvSince:Since:vvJDK1.0JDK1.0vvSeeAlso:SeeAlso:vvClassLoader.defineClass(byteClassLoader.defineClass(byteClassLoader.defineClass(byteClassLoader.defineClass(byte,intintintint,intintintint),SerializedFormSerializedFormfromF:J2SEdocsapijavalangClass.htmlfromF:J2SEdocsapijavalangClass.html3.2类
21、装载类装载vv缺省装载机制:缺省装载机制:Java运行系统根据需要加载相应的类。运行系统根据需要加载相应的类。当前引用的类编译后的字节码还未被加载当前引用的类编译后的字节码还未被加载时,通常使用时,通常使用“类路径类路径”(CLASSPATH)搜索字节码,并自动加载。搜索字节码,并自动加载。2.2类加载类加载vv手动加载机制手动加载机制通过使用一个通过使用一个ClassLoader对象来加载指定的类。对象来加载指定的类。staticClass forNameforName(StringclassName)Returns the Class object associated with the
22、class or interface with the given string name.Object newInstancenewInstance()Creates a new instance of the class represented by this Class object定义加载定义加载定义加载定义加载器器器器class class class class NetworkClassLoaderNetworkClassLoaderNetworkClassLoaderNetworkClassLoader extends extends extends extends ClassL
23、oaderClassLoaderClassLoaderClassLoader String host;String host;String host;String host;intintintint port;port;port;port;public Class public Class public Class public Class findClass(StringfindClass(StringfindClass(StringfindClass(String name)name)name)name)byte b=byte b=byte b=byte b=loadClassData(n
24、ameloadClassData(nameloadClassData(nameloadClassData(name););););return return return return defineClass(namedefineClass(namedefineClass(namedefineClass(name,b,0,b,0,b,0,b,0,b.lengthb.lengthb.lengthb.length););););private byte private byte private byte private byte loadClassData(StringloadClassData(
25、StringloadClassData(StringloadClassData(String name)name)name)name)/load the class data from the connection./load the class data from the connection./load the class data from the connection./load the class data from the connection.加载类加载类加载类加载类ClassLoaderClassLoaderClassLoaderClassLoader loader=new l
26、oader=new loader=new loader=new NetworkClassLoader(hostNetworkClassLoader(hostNetworkClassLoader(hostNetworkClassLoader(host,port);,port);,port);,port);Object main=Object main=Object main=Object main=loader.loadClass(Mainloader.loadClass(Mainloader.loadClass(Mainloader.loadClass(Main,true).newInstan
27、cetrue).newInstancetrue).newInstancetrue).newInstance();.();.();.();.2.3包装类包装类ObjectBooleanCharacterNumberClassByteShortIntegerLongFloatDoubleooclassclassjava.lang.java.lang.MathMath Booleanvvjava.langClassBooleanvvjava.lang.Objectjava.lang.Object java.lang.Booleanjava.lang.Boolean vvAllImplementedI
28、nterfaces:vvSerializableSerializable vvstaticstaticstaticstaticBooleanBooleanBooleanBooleanvalueOfvalueOfvalueOfvalueOf(boolean(boolean(boolean(booleanb)b)b)b)ReturnsaBooleaninstancerepresentingtheReturnsaBooleaninstancerepresentingthespecifiedspecifiedbooleanbooleanvalue.value.vvstaticstaticstatics
29、taticBooleanBooleanBooleanBooleanvalueOfvalueOfvalueOfvalueOf(StringStringStringStrings)s)s)s)ReturnsaReturnsaBooleanBooleanBooleanBooleanwithavaluerepresentedbythewithavaluerepresentedbythespecifiedString.specifiedString.Numbervvjava.langClassNumbervvjava.lang.Objectjava.lang.Object java.lang.Numbe
30、rjava.lang.Number vvAllImplementedInterfaces:vvSerializableSerializable vvDirectKnownSubclasses:vvBigDecimalBigDecimal,BigIntegerBigInteger,ByteByte,DoubleDouble,FloatFloat,IntegerInteger,LongLong,ShortShort NumbervvpublicabstractclassNumbervvextendsObjectvvimplementsSerializablevvTheabstractclassNu
31、mberNumberisthesuperclassofclassesBigDecimalBigDecimal,BigIntegerBigInteger,ByteByte,DoubleDouble,FloatFloat,IntegerInteger,LongLong,andShortShort.vvSubclassesofNumberNumbermustprovidemethodstoconverttherepresentednumericvaluetobytebyte,doubledouble,floatfloat,intint,longlong,andshortshort.Numbervvb
32、ytebytebytebytebyteValuebyteValuebyteValuebyteValue()()()()ReturnsthevalueofthespecifiednumberasaReturnsthevalueofthespecifiednumberasabytebytebytebyte.vvabstract double abstract double abstract double abstract double doubleValuedoubleValuedoubleValuedoubleValue()()()()Returnsthevalueofthespecifiedn
33、umberasaReturnsthevalueofthespecifiednumberasadoubledoubledoubledouble.vvabstract float abstract float abstract float abstract float floatValuefloatValuefloatValuefloatValue()()()()ReturnsthevalueofthespecifiednumberasaReturnsthevalueofthespecifiednumberasafloatfloatfloatfloat.vvabstract abstract ab
34、stract abstract intintintint intValueintValueintValueintValue()()()()ReturnsthevalueofthespecifiednumberasanReturnsthevalueofthespecifiednumberasanintintintint.vvabstract long abstract long abstract long abstract long longValuelongValuelongValuelongValue()()()()Returnsthevalueofthespecifiednumberasa
35、Returnsthevalueofthespecifiednumberasalonglonglonglong.vvshort short short short shortValueshortValueshortValueshortValue()()()()ReturnsthevalueofthespecifiednumberasaReturnsthevalueofthespecifiednumberasashortshortshortshort.Floatvvjava.langClassFloatvvjava.lang.Objectjava.lang.Object java.lang.Num
36、berjava.lang.Number java.lang.Floatjava.lang.Float vvAllImplementedInterfaces:vvComparable,SerializableFloatvvpublicfinalclassFloatvvextendsNumbervvimplementsComparablevvTheFloatFloatclasswrapsavalueofprimitivetypefloatfloatinanobject.AnobjectoftypeFloatFloatcontainsasinglefieldwhosetypeisfloatfloat
37、.vvInaddition,thisclassprovidesseveralmethodsforconvertingafloatfloattoaStringStringandaStringStringtoafloatfloat,aswellasotherconstantsandmethodsusefulwhendealingwithafloatfloat.Floatvvstatic float static float static float static float MAX_VALUEMAX_VALUEMAX_VALUEMAX_VALUE Aconstantholdingthelarges
38、tpositivefinitevalueoftypeAconstantholdingthelargestpositivefinitevalueoftypefloatfloatfloatfloat,(2-2,(2-2-23-23)2)2127127.vvstaticfloat staticfloat staticfloat staticfloat MIN_VALUEMIN_VALUEMIN_VALUEMIN_VALUE AconstantholdingthesmallestpositivenonzerovalueofAconstantholdingthesmallestpositivenonze
39、rovalueoftypetypefloatfloatfloatfloat,2,2-149-149.vvstaticfloat staticfloat staticfloat staticfloat NaNNaNNaNNaN AconstantholdingaNot-a-Number(AconstantholdingaNot-a-Number(NaNNaN)valueoftype)valueoftypefloatfloatfloatfloat.vvstaticfloat staticfloat staticfloat staticfloat NEGATIVE_INFINITYNEGATIVE_
40、INFINITYNEGATIVE_INFINITYNEGATIVE_INFINITY AconstantholdingthenegativeinfinityoftypeAconstantholdingthenegativeinfinityoftypefloatfloatfloatfloat.vvstaticfloat staticfloat staticfloat staticfloat POSITIVE_INFINITYPOSITIVE_INFINITYPOSITIVE_INFINITYPOSITIVE_INFINITY Aconstantholdingthepositiveinfinity
41、oftypeAconstantholdingthepositiveinfinityoftypefloatfloatfloatfloat.vvstaticstaticstaticstaticClassClassClassClass TYPETYPETYPETYPE TheTheClassClassClassClassinstancerepresentingtheprimitivetypeinstancerepresentingtheprimitivetypefloatfloatfloatfloat.4基础数据结构基础数据结构vv链表链表LinkedListvv堆栈堆栈Stackvv向量向量Vec
42、torvv树树TreeSetvv哈希表哈希表HashtableIterator接口的作用接口的作用vvpublicInterfaceIterator Boolean Boolean hasNexthasNext()()Returnstrueiftheiterationhasmoreelements.ObjectObject nextnext()()Returnsthenextelementintheiteration.void void removeremove()()Removesfromtheunderlyingcollectionthelastelementreturnedbytheit
43、erator(optionaloperation).LinkedList示例示例 import java.util.*;class StudentString name;int number;float score;Student(String name,int number,float score)this.name=name;this.number=number;this.score=score;public class LinkListThreepublic static void main(String args)LinkedList mylist=new LinkedList();S
44、tudent stu_1=new Student(赵好民,9012,80.0f),stu_2=new Student(钱小青,9013,90.0f),stu_3=new Student(孙力枚,9014,78.0f),stu_4=new Student(周左右,9015,55.0f);mylist.add(stu_1);mylist.add(stu_2);mylist.add(stu_3);mylist.add(stu_4);Iterator iter=mylist.iterator();while(iter.hasNext()Student te=(Student)iter.next();S
45、ystem.out.println(te.name+te.number+te.score);Stack示例示例importimportjava.utiljava.util.*;.*;classclassStackOneStackOne publicstaticvoidpublicstaticvoidmain(Stringmain(String argsargs)StackStackmystackmystack=newStack();=newStack();mystack.push(newmystack.push(newInteger(1);Integer(1);mystack.push(new
46、mystack.push(newInteger(2);Integer(2);mystack.push(newmystack.push(newInteger(3);Integer(3);mystack.push(newmystack.push(newInteger(4);Integer(4);mystack.push(newmystack.push(newInteger(5);Integer(5);mystack.push(newmystack.push(newInteger(6);Integer(6);while(!(mystack.emptywhile(!(mystack.empty()()
47、Integertemp=(Integertemp=(Integer)mystack.popInteger)mystack.pop();();System.out.printSystem.out.print(+(+temp.toStringtemp.toString();();Vector示例示例importjava.util.*;classExamplepublicstaticvoidmain(Stringargs)Vectorvector=newVector();Datedate=newDate();vector.add(newInteger(1);vector.add(newFloat(3
48、.45f);vector.add(newDouble(7.75);vector.add(newBoolean(true);vector.add(date);System.out.println(vector.size();Integernumber1=(Integer)vector.get(0);System.out.println(向量的第向量的第1个元素:个元素:+number1.intValue();Floatnumber2=(Float)vector.get(1);System.out.println(向量的第向量的第2个元素:个元素:+number2.floatValue();Dou
49、blenumber3=(Double)vector.get(2);System.out.println(向量的第向量的第3个元素:个元素:+number3.doubleValue();Booleannumber4=(Boolean)vector.get(3);System.out.println(向量的第向量的第4个元素:个元素:+number4.booleanValue();date=(Date)vector.lastElement();System.out.println(向量的第向量的第5个元素:个元素:+date.toString();if(vector.contains(date)S
50、ystem.out.println(ok);TreeSet示例示例 importimportjava.utiljava.util.*;.*;classclassTreeOneTreeOnepublicstaticvoidpublicstaticvoidmain(Stringmain(String argsargs)TreeSetTreeSet mytreemytree=new=newTreeSetTreeSet();();mytree.add(boy);mytree.add(zoomytree.add(boy);mytree.add(zoo););mytree.add(applemytree.