仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 1086|回复: 19
打印 上一主题 下一主题

[学习教程] JAVA网站制作之Declarations and Access Control (2)

[复制链接]
变相怪杰 该用户已被删除
跳转到指定楼层
楼主
发表于 2015-1-18 11:55:33 | 显示全部楼层 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
比如模式、敏捷方法什么的,这些思想好,但是实施的人没有理解而且没有正确运用这些知识导致了开发周期的延长。比如说对象,通过getName()方法不能获取对象的名字。accessObjective2
Declareclasses,innerclasses,methods,instancevariablesstatic,variablesandautomatic(methodlocal)variables,makingappropriateuseofallpermittedmodifiers(suchaspublicfinalstaticabstractandsoforth).Statethesignificanceofeachofthesemodifiersbothsinglyandincombinationandstatetheeffectofpackagerelationshipsondeclareditemsqualifiedbythesemodifiers.
1.Twotypesofvariables.
1.Membervariables
・Accessibleanywhereintheclass.
・Automaticallyinitializedbeforeinvokinganyconstructor.
・Staticvariablesareinitializedatclassloadtime.
・Canhavethesamenameastheclass.
2.Automaticvariables(methodlocal)
・Mustbeinitializedexplicitly.(compilerwillcatchitwhenusing,butdoesn’tcatchitifnousing)Objectreferencescanbeinitializedtonulltomakethecompilerhappy.
・Canhavethesamenameasamembervariable,resolutionisbasedonscope.
・Canonlybefinal.Notothermodifiers.

2.ModifiersareJavakeywordsthatprovideinformationtocompileraboutthenatureofthecode,dataandclasses.ThevisibilitymodifiersarepartoftheencapsulationmechanismforJava.Encapsulationallowsseparationoftheinterfacefromtheimplementationofmethods.


3.AccessmodifiersCpublic,protected,private
・Onlyappliedtoclasslevelvariables.(Methodvariablesarevisibleonlyinsidethemethod.)
・Canbeappliedtoclassitself(onlytoinnerclassesdeclaredatclasslevel,nosuchthingasprotectedorprivatetoplevelclass)
・Canbeappliedtomethodsandconstructors.
・Ifaclassisaccessible,itdoesn’tmean,themembersarealsoaccessible.Butiftheclassisnotaccessible,themembersarenotaccessible,eventhoughtheyaredeclaredpublic.
・Ifnoaccessmodifierisspecified,thentheaccessibilityisdefaultpackagevisibility.Allclassesinthesamepackagecanaccessthefeature.It’scalledasfriendlyaccess.ButfriendlyisnotaJavakeyword.SamedirectoryissamepackageinJava’sconsideration.
・Onlyoneouterclassperfilecanbedeclaredpublic.Ifyoudeclaremorethanoneclassinafiletobepublic,acompiletimeerrorwilloccur.
・‘private’meansonlytheclasscanaccessit,notevensub-classes.So,it’llcauseaccessdenialtoasub-class’sownvariable/method.
・Thesemodifiersdictate,whichclassescanaccessthefeatures.Aninstanceofaclasscanaccesstheprivatefeaturesofanotherinstanceofthesameclass.
・‘protected’meansallclassesinthesamepackage(likedefault)andsub-classesinanypackagecanaccessthefeatures.Butasubclassinanotherpackagecanaccesstheprotectedmembersinthesuper-classviaonlythereferencesofsubclassoritssubclasses.Asubclassinthesamepackagedoesn’thavethisrestriction.Thisensuresthatclassesfromotherpackagesareaccessingonlythemembersthatarepartoftheirinheritancehierarchy.
・Methodscannotbeoverriddentobemoreprivate.Onlythedirectionshowninfollowingfigureispermittedfromparentclassestosub-classes.

privateàfriendly(default)àprotectedàpublic

ParentclassesSub-classes

4.final
・finalclassescannotbesub-classed.
・finalvariablescannotbechanged.
・finalmethodscannotbeoverridden.Anymethodsinafinalclassareautomaticallyfinal.
・Methodargumentsmarkedfinalareread-only.Compilererror,iftryingtoassignvaluestofinalargumentsinsidethemethod.
・Finalvariablesthatarenotassignedavalueatthedeclarationandmethodargumentsthataremarkedfinalarecalledblankfinalvariables.Trytouseblankfinalvariableswillgivecompileerror.Theycanonlybeassignedavalueatmostonceinallconstructororinitializedblock.
・Staticfinalvariableshavetobeassignedatthedeclarationtimeorinstaticinitializedblock.
・Localvariablescanbedeclaredfinalaswell.

5.abstract
・Canbeappliedtoclassesandmethods.
・Oppositeoffinal,abstractmustbesub-classed.
・Aclassshouldbedeclaredabstract,
1.ifithasanyabstractmethods.
2.ifitdoesn’tprovideimplementationtoanyoftheabstractmethodsitinherited
3.ifitdoesn’tprovideimplementationtoanyofthemethodsinaninterfacethatitsaysimplementing.
・Justterminatetheabstractmethodsignaturewitha‘;’,curlybraceswillgiveacompilererror.
・Aclasscanbeabstractevenifitdoesn’thaveanyabstractmethods.
・Abstractmethodsmaynotbestatic,final,private,native,synchonized.
・Aclassthatisabstractmaynotbeinstantiated(ie,youmaynotcallitsconstructor,butinsubclass’sconstructor,super()works)

6.static
・Canbeappliedtonestedclasses,methods,variables,freefloatingcode-block(staticinitializer)
・staticmeansoneperclass,notoneforeachobjectnomatterhowmanyinstanceofaclassmight
exist.Thismeansthatyoucanusethemwithoutcreatinganinstanceofaclass.
・Staticvariablesareinitializedatclassloadtime.Aclasshasonlyonecopyofthesevariables.
・Staticmethodscanaccessonlystaticvariables.(Theyhavenothis)
・Accessbyclassnameisarecommendedwaytoaccessstaticmethods/variables.
・Staticmethodsmaynotbeoverriddentobenon-static.
・Non-staticmethodsmaynotbeoverriddentobestatic.
・Localvariablescannotbedeclaredasstatic.
・Actually,staticmethodsarenotparticipatingintheusualoverridingmechanismofinvokingthemethodsbasedontheclassoftheobjectatruntime.Staticmethodbindingisdoneatcompiletime,sothemethodtobeinvokedisdeterminedbythetypeofreferencevariableratherthantheactualtypeoftheobjectitholdsatruntime.

publicclassStaticOverridingTest{
publicstaticvoidmain(Strings[]){
Childc=newChild();
c.doStuff();//ThiswillinvokeChild.doStuff()
Parentp=newParent();
p.doStuff();//ThiswillinvokeParent.doStuff()
p=c;
p.doStuff();//ThiswillinvokeParent.doStuff(),ratherthanChild.doStuff()
}
}

classParent{
staticintx=100;
publicstaticvoiddoStuff(){
System.out.println("InParent..doStuff");
System.out.println(x);
}
}

classChildextendsParent{
staticintx=200;
publicstaticvoiddoStuff(){
System.out.println("InChild..doStuff");
System.out.println(x);
}
}


7.native
・Canbeappliedtomethodsonly.(staticmethodsalso)
・Writteninanon-Javalanguage,compiledforasinglemachinetargettype.
・JavaclassesuselotofnativemethodsforperformanceandforaccessinghardwareJavaisnotawareof.
・Nativemethodsignatureshouldbeterminatedbya‘;’,curlybraceswillprovideacompilererror.
・nativedoesn’taffectaccessqualifiers.Nativemethodscanbeprivate.
・abstractcanappearwithnativedeclaration.Thisforcestheentireclasstobeabstract.(obviously)
・Canpass/returnJavaobjectsfromnativemethods.
・System.loadLibraryisusedinstaticinitializercodetoloadnativelibraries.Ifthelibraryisnotloadedwhenthestaticmethodiscalled,anUnsatisfiedLinkErroristhrown.

8.transient
・Canbeappliedtoclasslevelvariablesonly.(Localvariablescannotbedeclaredtransient)
・Variablesmarkedtransientareneverserialized.(Staticvariablesarenotserializedanyway.)
・Notstoredaspartofobject’spersistentstate,i.e.notwrittenoutduringserialization.
・Canbeusedforsecurity.

9.synchronized
・Canbeappliedtomethodsorpartsofmethodsonly.
・Usedtocontrolaccesstocriticalcodeinmulti-threadedprograms.

10.volatile
・Canbeappliedtovariablesonly.
・Canbeappliedtostaticvariables.
・Cannotbeappliedtofinalvariables.
・Declaringavariablevolatileindicatesthatitmightbemodifiedasynchronously,sothatallthreadswillgetthecorrectvalueofthevariable.
・Usedinmulti-processorenvironments.

ModifierClassInnerclasses(Exceptlocalandanonymousclasses)VariableMethodConstructorFreefloatingCodeblock
publicYYY(notlocal)YYN
protectedNYY(notlocal)YYN
(friendly)NoaccessmodifierYY(OKforall)YYYN
privateNYY(notlocal)YYN
finalYY(Exceptanonymousclasses)YYNN
abstractYY(Exceptanonymousclasses)NYNN
staticNYY(notlocal)YNY(staticinitializer)
nativeNNNYNN
transientNNY(notlocal)NNN
synchronizedNNNYNY(partofmethod,alsoneedtospecifyanobjectonwhichalockshouldbeobtained)
volatileNNYNNN

Objective3
Foragivenclass,determineifadefaultconstructorwillbecreatedandifsostatetheprototypeofthatconstructor.

ConstructorsandSub-classing
・Constructorsarenotinheritedasnormalmethods,theyhavetobedefinedintheclassitself.
・Constructorshavesamenamewiththeclass,noreturntype.Amethodwithaclassname,butwithareturntypeisjustamethodbycompiler.Expecttrickquestionsusingthis.
・Ifyoudefinenoconstructorsatall,thenthecompilerprovidesadefaultconstructorwithnoargumentsandsamemodifierwithclass.
・Wecan’tcompileasub-classiftheimmediatesuper-classdoesn’thaveanoargumentdefaultconstructor,andsub-classconstructorsarenotcallingsuperorthisexplicitly(andexpectthecompilertoinsertanimplicitsuper()call)
・Aconstructorcancallotheroverloadedconstructorsby‘this(arguments)’.Ifyouusethis,itmustbethefirststatementintheconstructor.
・Aconstructorcan’tcallthesameconstructorfromwithin.Compilerwillsay‘recursiveconstructorinvocation’
・Aconstructorcancalltheparentclassconstructorexplicitlybyusing‘super(arguments)’.Ifyoudothis,itmustbefirstthestatementintheconstructor.
・Obviously,wecan’tuseboththisandsuperinthesameconstructor.Ifcompilerseesathisorsuper,itwon’tinsertadefaultcalltosuper().
・Constructorbodycanhaveanemptyreturnstatement.
・Onlymodifiersthataconstructorcanhavearetheaccessibilitymodifiers.

・Initializersareusedininitializationofobjectsandclassesandtodefineconstantsininterfaces.Theseinitializersare:
1.StaticandInstancevariableinitializerexpressions.
Literalsandmethodcallstoinitializevariables.Staticvariablescanbeinitialized
onlybystaticmethodcalls.
Cannotpassonthecheckedexceptions.Mustcatchandhandlethem.
2.Staticinitializerblocks.
Usedtoinitializestaticvariablesandloadnativelibraries.
Cannotpassonthecheckedexceptions.Mustcatchandhandlethem.
3.Instanceinitializerblocks.
Usedtofactoroutcodethatiscommontoalltheconstructors.
Alsousefulwithanonymousclassessincetheycannothaveconstructors.
Allconstructorsmustdeclaretheuncaughtcheckedexceptions,ifany.
InstanceInitializersinanonymousclassescanthrowanyexception.(?)
・Inalltheinitializers,forwardreferencingofvariablesisnotallowed.Forwardreferencingofmethodsisallowed.
・Orderofcodeexecution(whencreatinganobject)isabittricky.
1.staticvariablesinitialization.
2.staticinitializerblockexecution.(intheorderofdeclaration,ifmultipleblocksfound)
3.constructorheader(superorthisCimplicitorexplicit)
4.instancevariablesinitialization/instanceinitializerblock(s)execution
5.restofthecodeintheconstructor

Objective4
Statethelegalreturntypesforanymethodgiventhedeclarationsofallrelatedmethodsinthisorparentclasses.
Seemynote_6foroverloeadingandoverridden.
Examples:
Q1.
Assumewehavethefollowingcodeinthefile/abc/def/Q.java:
//File:/abc/def/Q.java:
packagedef;

publicclassQ{
privateintprivateVar;
intpackageVar;
protectedintprotectedVar;
publicintpublicVar;
}
andthiscodeisin/abc/Sub.java:
//File:/abc/Sub.java:
publicclassSubextendsTester{
}
andthiscodeisin/abc/Tester.java:
//File:/abc/Tester.java:
importdef.Q;

publicclassTesterextendsQ{
Qq=newQ();
Subsub=newSub();

publicvoidsomeMethod(){
//First,trytorefertoqsmemebers.
q.privateVar=1;//compilererror
q.packageVar=2;//compilererror
q.protectedVar=3;//compilererror
q.publicVar=4;//fine

//Next,trytorefertothisobjectsmembers
//suppliedbyclassQ.
privateVar=5;//compilererror
packageVar=6;//compilererror
protectedVar=7;//fine
publicVar=8;//fine

//Next,letstrytoaccessthemembersof
//anotherinstanceofTester.
Testert=newTester();
t.privateVar=9;//compilererror
t.packageVar=10;//compilererror
t.protectedVar=11;//fine
t.publicVar=12;//fine

//Finally,trytorefertothemembersina
//subclassofTester.
sub.privateVar=13;//compilererror
sub.packageVar=14;//compilererror
sub.protectedVar=15;//fine
sub.publicVar=16;//fine
}
}
Q2
Determinetheresultofattemptingtocompileandrunthefollowingcode:
classA{
publicA(){
System.out.println("AAA");
}
{
System.out.println("456");
}
}

publicclassBextendsA{
B(){
this(12);
System.out.println("BBB");
}
B(intx){
System.out.println("CCC");
}
{
System.out.println("123");
}
publicstaticvoidmain(String[]args){
newB();
}
}

Theoutputis:
456
AAA
123
CCC
BBB
Q3
Determinetheresultofattemptingtocompileandrunthefollowingcode:
classA{
publicintAvar;
publicA(){
System.out.println("AAA");
doSomething();
}
publicvoiddoSomething(){
Avar=1111;
System.out.println("A.doSomething()");
}
}

publicclassBextendsA{
publicintBvar=2222;
publicB(){
System.out.println("BBB");
doSomething();
System.out.println("Avar="+Avar);
}
publicvoiddoSomething(){
System.out.println("Bvar="+Bvar);
}
publicstaticvoidmain(String[]args){
newB();
}
}

Theoutputis:
AAA
Bvar=0
BBB
Bvar=2222
Avar=0
Q4
Aclassisnotabstractifitimplementsallsuperinterfaceseitherdirectlyorinherited
fromsuperclass.

eg.classa{voidmethod(){}}
interfaceab{voidmethod();}
classabcextendsaimplementsab{}//PERFECTLYLEGALsincesuperclasshas
implementedtheinterfacemethodsignature.


认真的记,感觉很紧张根本就没有时间和能力,来对技术知识点进行思考。这样课下就只能对知识进行简单的理解,其实简单的理解就是记忆课堂上讲的知识点,
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-5-11 12:32

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表