马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
还得说上一点,就java本质而言,是面相对象的,但是你有没有发现,java也不全是,比如说基本类型,int,那他就是整型而不是对象,转换类型是还得借助包装类。loading|objectObjective3)
Writecodetoconstructinstancesofanyconcreteclassincludingnormaltoplevelclassesinnerclassesstaticinnerclassesandanonymousinnerclasses.
InnerClasses
・Aclasscanbedeclaredinanyscope.Classesdefinedinsideofotherclassesareknownasnestedclasses.Therearefourcategoriesofnestedclasses.
Top-levelnestedclasses/interfaces
・Declaredasaclassmemberwithstaticmodifier.
・Justlikeotherstaticfeaturesofaclass.Canbeaccessed/instantiatedwithoutaninstanceoftheouterclass.Canaccessonlystaticmembersofouterclass.Can’taccessnon-staticinstancevariablesormethods.
・Verymuchlikeany-otherpackagelevelclass/interface.Provideanextensiontopackagingbythemodifiednamingschemeatthetoplevel.
・Classescandeclarebothstaticandnon-staticmembers.
・Anyaccessibilitymodifiercanbespecified.
・Nestedinterfacesareimplicitlystatic(staticmodifieralsocanbespecified).Theycanhaveanyaccessibilitymodifier.Therearenonon-staticinner,localoranonymousinterfaces.
Non-staticinnerclasses
・Declaredasaclassmemberwithoutstatic.
・Aninstanceofanon-staticinnerclasscanexistonlywithaninstanceofitsenclosingclass.Soitalwayshastobecreatedwithinacontextofanouterinstance.
Outer.Inneri=newOuter().newInner();
・Justlikeothernon-staticfeaturesofaclass.Canaccessallthefeatures(evenprivate)oftheenclosingouterclass.Haveanimplicitreferencetotheenclosinginstance.
・Cannothaveanystaticmembers.
・Canhaveanyaccessmodifier.
Localclasses
・Definedinsideablock(couldbeamethod,aconstructor,alocalblock,astaticinitializeroraninstanceinitializer).Cannotbespecifiedwithstaticmodifier.
・Cannothaveanyaccessmodifier(sincetheyareeffectivelylocaltotheblock)
・Cannotdeclareanystaticmembers.(Evendeclaredinastaticcontext)
・Canaccessallthefeaturesoftheenclosingclass(becausetheyaredefinedinsidethemethodoftheclass)butcanaccessonlyfinalvariablesdefinedinsidethemethod(includingmethodarguments).Thisisbecausetheclasscanoutlivethemethod,butthemethodlocalvariableswillgooutofscopeCincaseoffinalvariables,compilermakesacopyofthosevariablestobeusedbytheclass.(Newmeaningforfinal)
・Sincethenamesoflocalclassesarenotvisibleoutsidethelocalcontext,referencesoftheseclassescannotbedeclaredoutside.Sotheirfunctionalitycouldbeaccessedonlyviasuper-classreferences(eitherinterfacesorclasses).Objectsofthoseclasstypesarecreatedinsidemethodsandreturnedassuper-classtypereferencestotheoutsideworld.Thisisthereasonthattheycanonlyaccessfinalvariableswithinthelocalblock.Thatway,thevalueofthevariablecanbealwaysmadeavailabletotheobjectsreturnedfromthelocalcontexttooutsideworld.
・Cannotbespecifiedwithstaticmodifier.Butiftheyaredeclaredinsideastaticcontextsuchasastaticmethodorastaticinitializer,theybecomestaticclasses.Theycanonlyaccessstaticmembersoftheenclosingclassandlocalfinalvariables.Butthisdoesn’tmeantheycannotaccessanynon-staticfeaturesinheritedfromsuperclasses.Thesefeaturesaretheirown,obtainedviatheinheritancehierarchy.Theycanbeaccessednormallywith‘this’or‘super’.
Anonymousclasses
・Anonymousclassesaredefinedwheretheyareconstructed.Theycanbecreatedwhereverareferenceexpressioncanbeused.
・Ananonymousclassisneverabstract.Ananonymousclassisalwaysaninnerclass;itisneverstatic.Ananonymousclassisalwaysimplicitlyfinal.
・Anonymousclassescannothaveexplicitconstructors.Instanceinitializerscanbeusedtoachievethefunctionalityofaconstructor.
・Anonymousclassescanimplementaninterface(implicitextensionofObject)orexplicitlyextendaclass.Cannotdoboth.
Syntax:newinterfacename(){}ornewclassname(cantakearg.){}
・Keywordsimplementsandextendsarenotusedinanonymousclasses.
・Abstractclassescanbespecifiedinthecreationofananonymousclass.Thenewclassisaconcreteclass,whichautomaticallyextendstheabstractclass.
・Discussionforlocalclassesonstatic/non-staticcontext,accessingenclosingvariables,anddeclaringstaticvariablesalsoholdsgoodforanonymousclasses.Inotherwords,anonymousclassescannotbespecifiedwithstatic,butbasedonthecontext,theycouldbecomestaticclasses.Inanycase,anonymousclassesarenotallowedtodeclarestaticmembers.Basedonthecontext,non-static/staticfeaturesofouterclassesareavailabletoanonymousclasses.Localfinalvariablesarealwaysavailabletothem.
・E.g.
btn.addActionListener(
newActionListener(){
voidActionPerformed(){System.out.println(s);}
}
)
・Oneenclosingclasscanhavemultipleinstancesofinnerclasses.
・Innerclassescanhavesynchronousmethods.Butcallingthosemethodsobtainsthelockforinnerobjectonly,nottheouterobject.Ifyouneedtosynchronizeaninnerclassmethodbasedonouterobject,outerobjectlockmustbeobtainedexplicitly.Locksoninnerobjectandouterobjectareindependent.
・Nestedclassescanextendanyclassorcanimplementanyinterface.Norestrictions.
・Allnestedclasses(exceptanonymousclasses)canbeabstractorfinal.
・Classescanbenestedtoanydepth.Top-levelstaticclassescanbenestedonlywithinotherstatictop-levelclassesorinterfaces.Deeplynestedclassesalsohaveaccesstoallvariablesoftheouter-mostenclosingclass(aswelltheimmediateenclosingclass’s)
・Memberinnerclassescanbeforwardreferenced.Localinnerclassescannotbe.(?)
・Outerclassvariablesareaccessiblewithintheinnerclass,buttheyarenotinherited.Theydon’tbecomemembersoftheinnerclass.Thisisdifferentfrominheritance.(Outerclasscannotbereferredusing‘super’,andouterclassvariablescannotbeaccessedusing‘this’)
・Aninnerclassvariablecanshadowanouterclassvariable.Iftheinnerclassissub-classedwithinthesameouterclass,thevariablehastobequalifiedexplicitlyinthesub-class.Tofullyqualifythevariable,use(classname.this.variablename).Ifwedon’tcorrectlyqualifythevariable,acompilererrorwilloccur.(Notethatthisdoesnothappeninmultiplelevelsofinheritancewhereanupper-mostsuper-class’svariableissilentlyshadowedbythemostrecentsuper-classvariableorinmultiplelevelsofnestedinnerclasseswhereaninner-mostclass’svariablesilentlyshadowsanouter-mostclass’svariable.Problemcomesonlywhenthesetwohierarchychains(inheritanceandcontainment)clash.)
・Iftheinnerclassissub-classedoutsideoftheouterclass(onlypossiblewithtop-levelnestedclasses)explicitqualificationisnotneeded(itbecomesregularclassinheritance)
・Innerclasscannothavesomenameasanyofitsenclosingclass.
EntityDeclarationContextAccessibilityModifiersOuterinstanceDirectAccesstoenclosingcontextDefinesstaticornon-staticmembers
PackagelevelclassAspackagememberPublicordefaultNoN/ABothstaticandnon-static
Toplevelnestedclass(static)AsstaticclassmemberAllNoStaticmembersinenclosingcontextBothstaticandnon-static
NonstaticinnerclassAsnon-staticclassmemberAllYesAllmembersinenclosingcontextOnlynon-static
Localclass(non-static)Inblockwithnon-staticcontextNoneYesAllmembersinenclosingcontext+localfinalvariablesOnlynon-static
Localclass(static)InblockwithstaticcontextNoneNoStaticmembersinenclosingcontext+localfinalvariablesOnlynon-static
Anonymousclass(non-static)Inblockwithnon-staticcontextNoneYesAllmembersinenclosingcontext+localfinalvariablesOnlynon-static
Anonymousclass(static)InblockwithstaticcontextNoneNoStaticmembersinenclosingcontext+localfinalvariablesOnlynon-static
PackagelevelinterfaceAspackagememberPublicordefaultNoN/AStaticvariablesandnon-staticmethodprototypes
Toplevelnestedinterface(static)AsstaticclassmemberAllNoStaticmembersinenclosingcontextStaticvariablesandnon-staticmethodprototypes
//Example1
publicclassInnerInnerTest{
publicstaticvoidmain(Strings[]){
newOuter().newInner().newInnerInner().newInnerInnerInner().doSomething();
newOuter().newInnerChild().doSomething();
newOuter2().newInner2().newInnerInner2().doSomething();
newInnerChild2().doSomething();
}
}
classOuter{
Stringname="Vel";
classInner{
Stringname="Sharmi";
classInnerInner{
classInnerInnerInner{
publicvoiddoSomething(){
//Noprobleminaccessingwithoutfullqualification,
//inner-mostclassvariableshadowstheouter-mostclassvariable
System.out.println(name);//Prints"Sharmi"
System.out.println(Outer.this.name);//Prints"Vel",explicitreferencetoOuter
//error,variableisnotinheritedfromtheouterclass,itcanbejustaccessible
//System.out.println(this.name);
//System.out.println(InnerInner.this.name);
//System.out.println(InnerInnerInner.this.name);
//error,supercannotbeusedtoaccessouterclass.
//superwillalwaysrefertheparent,inthiscaseObject
//System.out.println(super.name);
System.out.println(Inner.this.name);//Prints"Sharmi",Innerhasdeclaredname
}
}
}
}
/*Thisisaninnerclassextendinganinnerclassinthesamescope*/
classInnerChildextendsInner{
publicvoiddoSomething(){
//compilererror,explicitqualifierneeded
//nameisinheritedfromInner,Outersnameisalsoinscope
//System.out.println(name);
System.out.println(Outer.this.name);//prints"Vel",explicitreferencetoOuter
System.out.println(super.name);//prints"Sharmi",Innerhasdeclaredname
System.out.println(this.name);//prints"Sharmi",nameisinheritedbyInnerChild
}
}
}
classOuter2{
staticStringname="Vel";
staticclassInner2{
staticStringname="Sharmi";
classInnerInner2{
publicvoiddoSomething(){
System.out.println(name);//prints"Sharmi",inner-mosthidesouter-most
System.out.println(Outer2.name);//prints"Vel",explicitreferencetoOuter2sstaticvariable
//System.out.println(this.name);//error,nameisnotinherited
//System.out.println(super.name);//error,superreferstoObject
}
}
}
}
/*Thisisastand-aloneclassextendinganinnerclass*/
classInnerChild2extendsOuter2.Inner2{
publicvoiddoSomething(){
System.out.println(name);//prints"Sharmi",Inner2snameisinherited
System.out.println(Outer2.name);//prints"Vel",explicitreferencetoOuter2sstaticvariable
System.out.println(super.name);//prints"Sharmi",Inner2hasdeclaredname
System.out.println(this.name);//prints"Sharmi",nameisinheritedbyInnerChild2
}
}
//Example2
publicclassInnerTest2{
publicstaticvoidmain(Strings[]){
newOuterClass().doSomething(10,20);
//Thisislegal
//OuterClass.InnerClassic=newOuterClass().newInnerClass();
//ic.doSomething();
//Compilererror,localinnerclassescannotbeaccessedfromoutside
//OuterClass.LocalInnerClasslic=newOuterClass().newLocalInnerClass();
//lic.doSomething();
newOuterClass().doAnonymous();
}
}
classOuterClass{
finalinta=100;
privateStringsecret="Nothingserious";
publicvoiddoSomething(intarg,finalintfa){
finalintx=100;
inty=200;
System.out.println(this.getClass()+"-indoSomething");
System.out.print("a="+a+"secret="+secret+"arg="+arg+"fa="+fa);
System.out.println("x="+x+"y="+y);
//Compilererror,forwardreferenceoflocalinnerclass
//newLocalInnerClass().doSomething();
abstractclassAncestorLocalInnerClass{}//innerclasscanbeabstract
finalclassLocalInnerClassextendsAncestorLocalInnerClass{//canbefinal
publicvoiddoSomething(){
System.out.println(this.getClass()+"-indoSomething");
System.out.print("a="+a);
System.out.print("secret="+secret);
//System.out.print("arg="+arg);//Compilererror,accessingnon-finalargument
System.out.print("fa="+fa);
System.out.println("x="+x);
//System.out.println("y="+y);//Compilererror,accessingnon-finalvariable
}
}
newInnerClass().doSomething();//forwardreferencefineformemberinnerclass
newLocalInnerClass().doSomething();
}
abstractclassAncestorInnerClass{}
interfaceInnerInterface{finalintsomeConstant=999;}//innerinterface
classInnerClassextendsAncestorInnerClassimplementsInnerInterface{
publicvoiddoSomething(){
System.out.println(this.getClass()+"-indoSomething");
System.out.println("a="+a+"secret="+secret+"someConstant="+someConstant);
}
}
publicvoiddoAnonymous(){
//Anonymousclassimplementingtheinnerinterface
System.out.println((newInnerInterface(){}).someConstant);
//Anonymousclassextendingtheinnerclass
(newInnerClass(){
publicvoiddoSomething(){
secret="secretischanged";
super.doSomething();
}
}).doSomething();
}
}
Thusanabstractclasscannotbeinstantiatedandsoanobjectreferencecannotbecreated.Rememberthataclassthatcontainsanyabstractmethodstheclassitselfisabstractandcannotbeinstantiated.
Alocalclassisvisibleonlywithinitscodeblockormethod.
Forclassinsideinterface:(?)
1.Theclassisalwayspublic.
2.Theclassisalwaysstatic.
3.theclassmethodscannotcallthemethodsdeclaredintheinterface.
Q1
publicclassMyClass1{
publicstaticvoidmain(Stringargv[]){}
/*ModifieratXX*/classMyInner{}
}
WhatmodifierswouldbelegalatXXintheabovecode?
1)public
2)private
3)static
4)friend
比如模式、敏捷方法什么的,这些思想好,但是实施的人没有理解而且没有正确运用这些知识导致了开发周期的延长。比如说对象,通过getName()方法不能获取对象的名字。 |