参考复试课件java lecture5_第1页
参考复试课件java lecture5_第2页
参考复试课件java lecture5_第3页
参考复试课件java lecture5_第4页
参考复试课件java lecture5_第5页
已阅读5页,还剩55页未读 继续免费阅读

下载本文档

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

文档简介

Objectives 5-

Inheritance

Inheritance(super/sub-class,protected,constructor)

Overriding,FieldHidingandSuper

FinalClassesandMethods(security,optimization)

CastandInstanceof

AbstractMethodsandClasses

Polymorphism

Design(Isa/HasA,accesscontrol)

KeyConcepts 5-

Inheritance: Reuse of proven and debuggedsoftware

Polymorphism: handle existing and yet-to-be-specified,andaddnewcapabilities

RelationshipsamongClasses

ISA:sub/super-class

HASA:composition,anobjecthasoneormoreobjectsofotherclassesasmembers

Coordination: operations by public fields &methods

Inheritance 5-

Subclass/Superclass

Directsuperclass/indirectsuperclass

SingleInheritance/multipleinheritance

InheritanceHierarchy(tree-like/network-like)

InheritanceandInterfacesinJava

Inheritance:classsubclassextendssuperclass

Object:allclassesaresubclassofObject(root)

Interfaces:achievemanyoftheadvantagesofmultipleinheritance

RelationshipbetweenSuperclassandSubclassObjects

Subclass-object-is-a-superclass-object

Asuperclassobjectisnotasubclassobject

Useanexplicitcasttoconvertasuperclassreferencetoa

subclassreference(Justastypecoercion)

PhoneCard 返回1

无卡号电话卡

对应电话机型号

拨打电话

查询余额

剩余金额

继承None_Number_PhoneCard

继承 返回2

有卡号电话卡

获得电话机型号

继承 继承

Number_PhoneCard

卡号、密码、接入号码、接通

继承

登录交换机

返回3

失效日期

200卡

附加费

电话磁卡

使用地域

拨打电话 magCard 拨打电话

拨打电话

修改密码

IC_Card 拨打电话

IP_Card

D2

0

0

C

ard

Example(1) 5-

abstractclassPhoneCard

{ doublebalance;

abstractbooleanperformDial();doublegetBalance()

{ returnbalance; }

}

abstractPhoneCard

class

None_Number_PhoneCard

extends

{

StringphoneSetType;

StringgetSetType()

{returnphoneSetType;

}

}

返回

Example(3) 5-

doublebalance;

classmagCardextendsNone_Number_PhoneCard

{

StringusefulArea;booleanperformDial()

{

if(balance>0.9)

{

}

else

balance-=0.9;returntrue;

returnfslase;

}

} 返回

ProgramminginJava

Example(3) 5-

classIC_CardextendsNone_Number_PhoneCard

{

booleanperformDial()

{

if(balance>0.5)

{

}

else

balance-=0.9;returntrue;

returnfalse;

}

} 返回

ProgramminginJava

Example(3) 5-

classIP_CardextendsNumber_PhoneCard

{

DateexpireDate;booleanperformDial()

{

if(balance>0.3&&expireDate.after(newDate()))

{

}

else

balance-=0.3;returntrue;

returnfalse;

}

} 返回

ProgramminginJava

Example(3) 5-

classD200_CardextendsNumber_PhoneCard

doublebalance;//Number_PhoneCard

{

doublebalance;doubleadditoryFee;booleanperformDial()

{ if(balance>(0.5+additoryFee))

{ balance-=(0.5+additoryFee);returntrue; }

else

reurnfalse; }

}

返回

ProgramminginJava

Example(2) 5-

abstractclassNumber_PhoneCardextendsPhoneCard

{ longcardNumber;intpassword;

StringconnectNumber;booleanconnected;

booleanperformConnection(longcn,intpw)

{if(cn==cardNumber&&pw==password)

{ connected=true;returntrue; }

else

returnfalse; }

} 返回

ProgramminginJava

ObjectClass 5-

TheObjectclassdefinesandimplementsbehaviorthateveryclassintheJavasystemneeds.Itisthemostgeneralofallclasses.

ThereferenceofObjectclassobjectcaninsteadofanyobject

Objectoref=newPixel();oref=“SomeString”

返回

Field 5-

FieldInheritance:magCard

FieldHiding

WhatisFieldHiding?

—Afieldwiththesamenameasasuperclass’sfiledisdeclaredinsubclass

Notes

—Thehiddenfieldinthesuperclassstillexists

—The hidden field may be accessed by super, orreferencingasuperclass’sobject

—Whenafieldofanobjectisaccessed,thedeclaredtype

oftheobjectdetermineeithersuper-orsub-class’sfield

willbeused

Example 5-

PublicclassTestHiddenField

{publicstaticvoidmain(Stringargs[])

{D200_Cardmy200=newD200_Card();my200.balance=50.0;

System.out.println(“Supper:”+my200.getBalance());

0.0

if(my200.performDial())

System.out.println(“Subclass:”+my200.balance);

49.5

}

}

Method 5-

MethodInheritance:IC-Card

Overriding

—Replaceasuperclass’smethodimplementationbyanewoneinthesubclass

—Requirements

Theoldmethodandthenewmethodmusthavethesamesignatureandreturntype.(ifdifferent,sucharedefinitionisnotoverriding,butissimplyanexampleofoverloading)

Themethodmustbenon-static

Notes 5-

Supermaybeusedtorefertotheoverriddenmethodofthesuperclass

Thethrowsclausesmaybedifferent:theoverridingmethodhasfewerexceptiontypes(ornothrows)

Theoverridingmethodmayhavenewmodifiers,butmustprovidemoreaccesspermissions.Ifprotectedinsuperclass,thenprotectedorpublic,mustnotbeprivateinsubclass

DynamicMethodCall:whenamethodofanobjectiscalled,theactualtypeoftheobjectdetermine

whichimplementationwillbeused

Example(1) 5-

classSuperShow{

publicStringstr=“SuperStr”;publicvoidshow(){

System.out.println(“Super.show:”+str);}

}

classExtendShowextendsSuperShow

{publicStringstr=“ExtendStr”;publicvoidshow(){

System.out.println(“Extend.show”+str); }publicstaticvoidmain(String[]args){

ExtendShowext=newExtendShow();SuperShowsup=ext;

ProgramminginJava

Example(2) 5-

sup.show();//showofactualtype,i.e.ExtendShowext.show();System.out.println(“sup.str=”+sup.str);System.out.println(“ext.str=”+ext.str);

}

}

Twokindsofreference:actualtype(ext),supertype(sup)

Result:Extend.show:ExtendStr //actualtype:Extend

Extend.show:ExtendStr

sup.str=SuperStr//declaredtype:SuperShow

ext.str=ExtendStr//declaredtype:ExtendShow

Supper 5-

Function

Referencethecurrentobjectasaninstanceofthesuperclass,whenaccessfieldsandmethods

Use

Super.variable

Super.Method([paramlist])

Super([paramlist])

Note:super.methodalwayscallthesuperclass’s(overridden)method,notthesubclass’s(overriding)method.Sothemethodtobeusedforsuperisdeterminedbyreferencetype,

notactualtype

ConstructorsinSubclasses 5-

SelectandInvokeaSuperclass’sConstructor

Explicitcall

super()isthefirststatementofnewconstructor

Automaticcall

Ifsuper()isnotthefirststatement,calltheno-argconstructorofthesuperclass.Ifthereisnosuchconstructor,anexplicitcallofsuperclass’sconstructorwithparametersmustbecalled

classAttr{

Example(1) 5-

privateStringname;privateObjectvalue=null;

publicAttr(StringnameOf){name=nameOf; }publicAttr(StringnameOf,ObjectvalueOf){

name=nameOf; value=valueOf;}publicStringnameOf(){ returnname; }publicObjectvalueOf(){ returnvalue; }publicStringvalueOf(ObjectnewValue)

{ObjectoldVal=value;

value=newValue;returnoldVal; }

}

Example(2) 5-

classColorAttrextendsAttr{

privateScreenColormyColor;//thedecodedcolor

publicColorAttr(Stringname,Objectvalue)

{super(name,value);decodeColor(); }publicColorAttr(Stringname)

{this(name,”transparent”);}

publicColorAttr(Stringname,ScreenColorvalue)

{super(name,value.toString());myColor=value; }

publicObjectvalueOf(ObjectnewValue){

//dothesuperclass’svalueOfworkfirst

Objectretval=super.valueOf(newValue);decodeColor();returnretval; }

/**SetvaluetoScreenColor,notdescription*/

NotesonConstructors 5-

“this()”cancallaconstructorintheclassitself

Subclassneednottohavethesameconstructorsignaturesassuperclass

Defaultconstructorofsubclassstartsbycallingtheno-argconstructorofthesuperclass

Ifthesuperclasshasnotanynon-argconstructor,subclassmustprovideatleastoneconstructor

Ifasuperclass’sconstructorcallsamethod,themethodwouldbemostlyoverriddeninsubclass

InitializingOrdersinSubclass 5-

Initializebydefault(0,\u0000,false,null),andcallthesubclass’sconstructor(i.e.thefollowing3steps)

Callthesuperclass’sconstructor

Initializebydeclarationassignment

Executethesubclass’sconstructorbody

Example(1) 5-

classYextendsX{

protectedintyMask=0xff00;publicY(){

fullMask|=yMask;

}

}

? How is a Y object to becreated?

ProgramminginJava

Example(2) 5-

Step Action xMask yMask fullMask

0 Default

0

0

0

1 CallYconstructor

0

0

0

2 CallXconstructor

0

0

0

3 InitializeXfields

0x00ff

0

0

4 ExecuteXConstructor

0x00ff

0

0x00ff

5 InitializeYfields

0x00ff

0xff00

0x00ff

6 ExecuteYconstructor

0x00ff

0xff00

0xffff

Example(3) 5-

classYextendsX{

protectedintyMask=0xff00;publicY(){

fullMask|=yMask;

}

}

classX{

protectedintxMask=0x00ff;protectedintfullMask;publicX(){

fullMask=mask(xMask);

}

publicintmask(intorig)

{return(orig&fullMask);

}

}

ProgramminginJava

ProgramminginJava

Example(4) 5-

Step Action xMask yMask fullMask

0 Default

0

0

0

1 CallYconstructor

0

0

0

2 CallXconstructor

0

0

0

3 InitializeXfields

0x00ff

0

0

4 ExecuteXConstructor

0x00ff

0

0

5 InitializeYfields

0x00ff

0xff00

0

6 ExecuteYconstructor

0x00ff

0xff00

0xff00

Example(5) 5-

classYextendsX{

protectedintyMask=0xff00;publicY(){

fullMask|=yMask;

}

publicintmask(intorig)

{return(orig|fullMask);

}

}

ProgramminginJava

Example(6) 5-

Step Action xMask yMask fullMask

0 Default

0

0

0

1 CallYconstructor

0

0

0

2 CallXconstructor

0

0

0

3 InitializeXfields

0x00ff

0

0

4 ExecuteXConstructor

0x00ff

0

0x00ff

5 InitializeYfields

0x00ff

0xff00

0x00ff

6 ExecuteYconstructor

0x00ff

0xff00

0xffff

FinalMethod&FinalClass 5-

FinalMethods

—Cannotbere-implemented(overridden)

—Thefinalversionofthemethod

—Staticandprivatemethodsareimplicitlyfinal

FinalClasses:PreventingInheritance

—Cannotbeextended(inherited)

—AllMethodsinafinalclassareimplicitlyfinal

Security 5-

Security:‘final’improvesthesecurity

Behavioroffinalmethodisdetermined,unlessitcallsnon-finalmethods

Theassociatedfieldsoffinalmethodshouldbeprivate,otherwisesubclassesmaychangethemethodbehaviorthroughchangingthesefields

Finalclassescannotbeextended(alsoadefect)

Usenon-finalclasswithmethodsallfinal,sothattheclasscanbeextended,butthemethodcannotbere-implemented

OptimizationandEfficiency 5-

Optimization:‘Final’simplifiestheoptimization

Somepublicstepsofmethodcallareomitted,e.g.Matchformal-actualpara.;Pushreturnaddr.tostack

Inlinethecode:Removingcallstofinalmethods,andreplacingthemwiththeexpandedcodeoftheirdefinitionsateachmethodcalllocation

Efficiency

‘Final’makessometypescheckedatcompiletime,typesfornon-finalreferencearecheckedatruntime

Dynamicbinding(suchasdynamicallyselectamethodimplementationfromseveralones)hasmoreoverhead

thanstaticbinding

Notation

Cast 5-

<type><var>=(<type>)<var>

Convertanobjectfromoneclasstoanother

Justastypecoercion(bymeansofcasts)

CastingUp(Widening)

Toassignasubclassobjecttoasuperclassvariable

Safecasting

CastingDown(Narrowing)

Toassignasuperclassobjecttoasubclassvariable

Unsafecasting(notalwaysvalid)

Ifanobjecthasbeenassignedtoareferenceofoneofitssuperclasses,it’sacceptabletocastthatobjectbacktoitsowntype

Employee:john;classManagerextendsEmployee,…

Managerboss=(Manager)john;

Example 5-

ClassA{

publicvoidf(){};staticvoidg(Ai){

i.f();} A

}

ClassBextendsA{

publicstaticvoidmain(String[]args){ BBb=newB();

A.g(b);

}

} 返回

TheInstanceofOperator 5-

TheOperator

IinstanceofC

IisaninstanceofclassC

Example

if(johninstanceofManager)

{Managerboss=(Manager)john;}

Note

nullinstanceofTypeisfalseforanyType

NotesonCast 5-

Castscanonlybeusedwithinaninheritancehierarchy

instanceofshouldbeusedtocheckhierarchybeforecastingfromaparenttoachild,otherwiseaclassCastExceptionoccurs

Performingacastisnotusuallyagoodidea,becausethedynamicbindingoftenautomaticallylocatesthecorrectmethod

AbstractMethod

Amethodhasnotbeenspecified(signatureonly)

Abstract methods must be implemented in non-abstractsubclasses

AbstractClass:oneormoreabstractmethods

Abstractclassesmayhaveconcretedataandmethods

Example

Notes

Noinstanceofabstractsuperclassescanbeinstantiated

Superclass’smethodsmaybeoverriddenbyabstractmethods(changeconcretetoabstract)

Theabstractmethodgivestheclassdesignerconsiderablepoweroverhowsubclasseswillbe

implementedinaclasshierarchy

Example(1) 5-

abstractclassGraphicObject

{intx,y;

...

voidmoveTo(intnewX,intnewY)

{...}

abstractvoiddraw();}

classCircleextendsGraphicObject

{voiddraw(){...}

}

Example(2) 5-

abstractclassA

{abstractvoidcallme();voidmetoo()

{System.out.println(“A’smetoo”)}

}

classBextendsA

{voidcallme()

{System.out.println(“M’scallme”)}

}

Aa=newB();a.callme();/*B’scallme*/a.metoo();

Methods

Overloading(methodswithdifferentsignatures)

Overriding(inheritancewithredefinition)

Types

Subclass-object-is-a-superclass-object,soanobjectcanbereferencedbythesupertypes

Aclass’sconstructorusuallyinvokesasuperclass’sconstructor,becausecreatinganobjectalsoleadstocreatinganotherobjectofthesuperclass

AvariableoftypeObjectmayrefertoanyobject

Example 5-

GraphicObjectg=newCircle();g.draw();

CastingUp

Circle.draw()

在C++中,用虚函数实现动态绑定;

在JAVA中,缺省情况就是动态绑定;否则可用final定义

Notes 5-

Polymorphis

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论