计算机专业论文译文对象传递文档格式.docx
- 文档编号:4080890
- 上传时间:2023-05-02
- 格式:DOCX
- 页数:53
- 大小:43.42KB
计算机专业论文译文对象传递文档格式.docx
《计算机专业论文译文对象传递文档格式.docx》由会员分享,可在线阅读,更多相关《计算机专业论文译文对象传递文档格式.docx(53页珍藏版)》请在冰点文库上搜索。
”Somehaveclaimedthatpointersarehardanddangerousandthereforebad,andsinceJavaisallgoodnessandlightandwillliftyourearthlyprogrammingburdens,itcannotpossiblycontainsuchthings.However,it’smoreaccuratetosaythatJavahaspointers;
indeed,everyobjectidentifierinJava(exceptforprimitives)isoneofthesepointers,buttheiruseisrestrictedandguardednotonlybythecompilerbutbytherun-timesystem.Ortoputitanotherway,Javahaspointers,butnopointerarithmetic.ThesearewhatI’vebeencalling“references,”andyoucanthinkofthemas“safetypointers,”notunlikethesafetyscissorsofelementaryschool—theyaren’tsharp,soyoucannothurtyourselfwithoutgreateffort,buttheycansometimesbeslowandtedious.
Passingreferencesaround
Whenyoupassareferenceintoamethod,you’restillpointingtothesameobject.Asimpleexperimentdemonstratesthis:
//:
appendixa:
PassReferences.java
//Passingreferencesaround.
importcom.bruceeckel.simpletest.*;
publicclassPassReferences{
privatestaticTestmonitor=newTest();
publicstaticvoidf(PassReferencesh){
System.out.println("
hinsidef():
"
+h);
}
publicstaticvoidmain(String[]args){
PassReferencesp=newPassReferences();
pinsidemain():
+p);
f(p);
monitor.expect(newString[]{
%%pinsidemain\\(\\):
PassReferences@[a-z0-9]+"
%%hinsidef\\(\\):
});
}///:
~
ThemethodtoString(
)isautomaticallyinvokedintheprintstatements,andPassReferencesinheritsdirectlyfromObjectwithnoredefinitionoftoString(
).Thus,Object’sversionoftoString(
)isused,whichprintsouttheclassoftheobjectfollowedbytheaddresswherethatobjectislocated(notthereference,buttheactualobjectstorage).Theoutputlookslikethis:
PassReferences@ad3ba4
Youcanseethatbothpandhrefertothesameobject.ThisisfarmoreefficientthanduplicatinganewPassReferencesobjectjustsothatyoucansendanargumenttoamethod.Butitbringsupanimportantissue.
Aliasing
Aliasingmeansthatmorethanonereferenceistiedtothesameobject,asintheprecedingexample.Theproblemwithaliasingoccurswhensomeonewritestothatobject.Iftheownersoftheotherreferencesaren’texpectingthatobjecttochange,they’llbesurprised.Thiscanbedemonstratedwithasimpleexample:
Alias1.java
//Aliasingtworeferencestooneobject.
publicclassAlias1{
privateinti;
publicAlias1(intii){i=ii;
Alias1x=newAlias1(7);
Alias1y=x;
//Assignthereference
x:
+x.i);
y:
+y.i);
Incrementingx"
);
x.i++;
7"
8"
}///
Intheline:
Alias1y=x;
anewAlias1referenceiscreated,butinsteadofbeingassignedtoafreshobjectcreatedwithnew,it’sassignedtoanexistingreference.Sothecontentsofreferencex,whichistheaddressoftheobjectxispointingto,isassignedtoy,andthusbothxandyareattachedtothesameobject.Sowhenx’siisincrementedinthestatement:
x.i++;
y’siwillbeaffectedaswell.Thiscanbeseenintheoutput:
7
Incrementingx
8
Onegoodsolutioninthiscaseissimplynottodoit;
don’tconsciouslyaliasmorethanonereferencetoanobjectatthesamescope.Yourcodewillbemucheasiertounderstandanddebug.However,whenyou’repassingareferenceinasanargument—whichisthewayJavaissupposedtowork—youautomaticallyalias,becausethelocalreferencethat’screatedcanmodifythe“outsideobject”(theobjectthatwascreatedoutsidethescopeofthemethod).Here’sanexample:
Alias2.java
//Methodcallsimplicitlyaliastheirarguments.
publicclassAlias2{
publicAlias2(intii){i=ii;
publicstaticvoidf(Alias2reference){reference.i++;
Alias2x=newAlias2(7);
Callingf(x)"
f(x);
Themethodischangingitsargument,theoutsideobject.Whenthiskindofsituationarises,youmustdecidewhetheritmakessense,whethertheuserexpectsit,andwhetherit’sgoingtocauseproblems.
Ingeneral,youcallamethodinordertoproduceareturnvalueand/orachangeofstateintheobjectthatthemethodiscalledfor.It’smuchlesscommontocallamethodinordertomanipulateitsarguments;
thisisreferredtoas“callingamethodforitssideeffects.”Thus,whenyoucreateamethodthatmodifiesitsarguments,theusermustbeclearlyinstructedandwarnedabouttheuseofthatmethodanditspotentialsurprises.Becauseoftheconfusionandpitfalls,it’smuchbettertoavoidchangingtheargument.
Ifyouneedtomodifyanargumentduringamethodcallandyoudon’tintendtomodifytheoutsideargument,thenyoushouldprotectthatargumentbymakingacopyinsideyourmethod.That’sthesubjectofmuchofthisappendix.
Makinglocalcopies
Toreview:
AllargumentpassinginJavaisperformedbypassingreferences.Thatis,whenyoupass“anobject,”you’rereallypassingonlyareferencetoanobjectthatlivesoutsidethemethod,soifyouperformanymodificationswiththatreference,youmodifytheoutsideobject.Inaddition:
●Aliasinghappensautomaticallyduringargumentpassing.
●Therearenolocalobjects,onlylocalreferences.
●Referenceshavescopes,objectsdonot.
●ObjectlifetimeisneveranissueinJava.
●Thereisnolanguagesupport(e.g.,“const”)topreventobjectsfrombeingmodifiedandstopthenegativeeffectsofaliasing.Youcan’tsimplyusethefinalkeywordintheargumentlist;
thatsimplypreventsyoufromrebindingthereferencetoadifferentobject.
Ifyou’reonlyreadinginformationfromanobjectandnotmodifyingit,passingareferenceisthemostefficientformofargumentpassing.Thisisnice;
thedefaultwayofdoingthingsisalsothemostefficient.However,sometimesit’snecessarytobeabletotreattheobjectasifitwere“local”sothatchangesyoumakeaffectonlyalocalcopyanddonotmodifytheoutsideobject.Manyprogramminglanguagessupporttheabilitytoautomaticallymakealocalcopyoftheoutsideobject,insidethemethod.[116]Javadoesnot,butitallowsyoutoproducethiseffect.
Passbyvalue
Thisbringsuptheterminologyissue,whichalwaysseemsgoodforanargument.Thetermis“passbyvalue,”andthemeaningdependsonhowyouperceivetheoperationoftheprogram.Thegeneralmeaningisthatyougetalocalcopyofwhateveryou’repassing,buttherealquestionishowyouthinkaboutwhatyou’repassing.Whenitcomestothemeaningof“passbyvalue,”therearetwofairlydistinctcamps:
1.Javapasseseverythingbyvalue.Whenyou’repassingprimitivesintoamethod,yougetadistinctcopyoftheprimitive.Whenyou’repassingareferenceintoamethod,yougetacopyofthereference.Ergo,everythingispassbyvalue.Ofcourse,theassumptionisthatyou’realwaysthinking(andcaring)thatreferencesarebeingpassed,butitseemsliketheJavadesignhasgonealongwaytowardallowingyoutoignore(mostofthetime)thatyou’reworkingwithareference.Thatis,itseemstoallowyoutothinkofthereferenceas“theobject,”sinceitimplicitlydereferencesitwheneveryoumakeamethodcall.
2.Javapassesprimitivesbyvalue(noargumentthere),butobjectsarepassedbyreference.Thisistheworldviewthatthereferenceisanaliasfortheobject,soyoudon’tthinkaboutpassingreferences,butinsteadsay“I’mpassingtheobject.”Sinceyoudon’tgetalocalcopyoftheobjectwhenyoupassitintoamethod,objectsareclearlynotpassedbyvalue.ThereappearstobesomesupportforthisviewwithinSun,sinceatonetime,oneofthe“reservedbutnotimplemented”keywordswasbyvalue(Thiswillprobablyneverbeimplemented).
Havinggivenbothcampsagoodairing,andaftersaying“Itdependsonhowyouthinkofareference,”Iwillattempttosidesteptheissue.Intheend,itisn’tthatimportant—whatisimportantisthatyouunderstandthatpassingareferenceallowsthecaller’sobjecttobechangedunexpectedly.
Cloningobjects
Themostlikelyreasonformakingalocalcopyofanobjectisifyou’regoingtomodifythatobjectandyoudon’twanttomodifythecaller’sobject.Ifyoudecideth
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 计算机专业 论文 译文 对象 传递
![提示](https://static.bingdoc.com/images/bang_tan.gif)