计算机专业外文翻译thinkinjava文档格式.docx
- 文档编号:18149630
- 上传时间:2022-12-13
- 格式:DOCX
- 页数:23
- 大小:31.50KB
计算机专业外文翻译thinkinjava文档格式.docx
《计算机专业外文翻译thinkinjava文档格式.docx》由会员分享,可在线阅读,更多相关《计算机专业外文翻译thinkinjava文档格式.docx(23页珍藏版)》请在冰豆网上搜索。
sfunctionalprogrammingfeaturesarecompelling,butthey'
renottheonlyreasonJavadevelopersshouldbeinterestedinthelanguage.Infact,Scalablendsfunctionalconceptsandobjectorientation.InordertolettheJava-cum-Scalaprogrammerfeelmoreathome,itmakessensetolookatScala'
sobjectfeaturesandseehowtheymapovertoJavalinguistically.Bearinmindthatthereisn'
tadirectmappingforsomeofthesefeatures,orinsomecases,the"
mapping"
ismoreofananalogthanadirectparallel.Butwherethedistinctionisimportant,I'
llpointitout.
Scalahasclass(es),too
RatherthanembarkonalengthyandabstractdiscussionoftheclassfeaturesthatScalasupports,let'
slookatadefinitionforaclassthatmightbeusedtobringrationalnumbersupporttotheScalaplatform(largelyswipedfrom"
ScalaByExample"
--seeResources):
Listing1.rational.scala
classRational(n:
Int,d:
Int)
{
privatedefgcd(x:
Int,y:
Int):
Int=
{
if(x==0)y
elseif(x<
0)gcd(-x,y)
elseif(y<
0)-gcd(x,-y)
elsegcd(y%x,x)
}
privatevalg=gcd(n,d)
valnumer:
Int=n/g
valdenom:
Int=d/g
def+(that:
Rational)=
newRational(numer*that.denom+that.numer*denom,denom*that.denom)
def-(that:
newRational(numer*that.denom-that.numer*denom,denom*that.denom)
def*(that:
newRational(numer*that.numer,denom*that.denom)
def/(that:
newRational(numer*that.denom,denom*that.numer)
overridedeftoString()=
"
Rational:
["
+numer+"
/"
+denom+"
]"
}
WhiletheoverallstructureofListing1islexicallysimilartowhatyou'
veseeninJavacodeoverthelastdecade,somenewelementsclearlyareatworkhere.Beforepickingthisdefinitionapart,takealookatthecodetoexercisethenewRationalclass:
Listing2.RunRational
classRational(n:
//...asbefore
objectRunRationalextendsApplication
valr1=newRational(1,3)
valr2=newRational(2,5)
valr3=r1-r2
valr4=r1+r2
Console.println("
r1="
+r1)
r2="
+r2)
r3=r1-r2="
+r3)
r4=r1+r2="
+r4)
WhatyouseeinListing2isn'
tterriblyexciting:
Icreateacoupleofrationalnumbers,createtwomoreRationalsastheadditionandsubtractionofthefirsttwo,andechoeverythingtotheconsole.(NotethatConsole.println()comesfromtheScalacorelibrary,livinginscala.*,andisimplicitlyimportedintoeveryScalaprogram,justasjava.langisinJavaprogramming.)
HowmanywaysshallIconstructthee?
NowlookagainatthefirstlineintheRationalclassdefinition:
Listing3.Scala'
sdefaultconstructor
//...
Althoughyoumightthinkyou'
relookingatsomekindofgenerics-likesyntaxinListing3,it'
sactuallythedefaultandpreferredconstructorfortheRationalclass:
nanddaresimplytheparameterstothatconstructor.
spreferenceforasingleconstructormakesacertainkindofsense--mostclassesenduphavingasingleconstructororacollectionofconstructorsthatall"
chain"
throughasingleconstructorasaconvenience.Ifyouwantedto,youcoulddefinemoreconstructorsonaRationallikeso:
Listing4.Achainofconstructors
defthis(d:
Int)={this(0,d)}
NotethatScala'
sconstructorchaindoestheusualJava-constructor-chainingthingbycallingintothepreferredconstructor(theInt,Intversion).
Details,(implementation)details...
Whenworkingwithrationalnumbers,ithelpstoperformabitofnumericallegerdemain:
namelythatoffindingacommondenominatortomakecertainoperationseasier.Ifyouwanttoadd1-over-2(alsoknownas"
one-half"
)to2-over-4(alsoknownas"
two-fourths"
),theRationalclassshouldbesmartenoughtorealizethat2-over-4isthesameas1-over-2,andconvertitaccordinglybeforeaddingthetwotogether.
Thisisthepurposeofthenestedprivategcd()functionandgvalueinsideoftheRationalclass.WhentheconstructorisinvokedinScala,theentirebodyoftheclassisevaluated,whichmeansgwillbeinitializedwiththegreatestcommondenominatorofnandd,andthenusedinturntosetnanddappropriately.
LookingbackatListing1,it'
salsofairlyeasytoseethatIcreatedanoverriddentoStringmethodtoreturnthevaluesofRational,whichwillbeveryusefulwhenIstartexercisingitfromtheRunRationaldrivercode.
NoticethesyntaxaroundtoString,however:
theoverridekeywordinthefrontofthedefinitionisrequiredsothatScalacanchecktomakesurethatacorrespondingdefinitionexistsinthebaseclass.Thiscanhelppreventsubtlebugscreatedbyaccidentalkeyboardslips.(Itwasthissamemotivationthatledtothecreationofthe@OverrideannotationinJava5.)Notice,aswell,thatthereturntypeisnotspecified--it'
sobviousfromthedefinitionofthemethodbody--andthatthereturnedvalueisn'
texplicitlydenotedusingthereturnkeyword,whichJavawouldrequire.Instead,thelastvalueinthefunctionisconsideredthereturnvalueimplicitly.(YoucanalwaysusereturnkeywordifyoupreferJavasyntax,however.)
Somecorevalues
Nextuparethedefinitionsofnumeranddenom,respectively.Thesyntaxinvolved,offhand,wouldleadtheJavaprogrammertobelievethatnumeranddenomarepublicIntfieldsthatareinitializedtothevalueofn-over-gandd-over-g,respectively;
butthisassumptionisincorrect.
Formally,Scalacallsnumeranddenommethodswithoutparameters,whichareusedtocreateaquick-and-easysyntaxfordefiningaccessors.TheRationalclassstillhasthreeprivatefields,n,d,andg,buttheyarehiddenfromtheworldbydefaultprivateaccessinthecaseofnandd,andbyexplicitprivateaccessinthecaseofg.
TheJavaprogrammerinyouisprobablyaskingatthispoint,"
Wherearethecorresponding"
setters"
fornandd?
"
Nosuchsettersexist.PartofthepowerofScalaisthatitencouragesdeveloperstocreateimmutableobjectsbydefault.Granted,syntaxisavailabletocreatemethodsformodifyingtheinternalsofRational,butdoingsowouldruintheimplicitthread-safenatureofthisclass.Asaresult,atleastforthisexample,I'
mgoingtoleaveRationalasitis.
Naturally,thatraisesthequestionofhowonemanipulatesaRational.Likejava.lang.Strings,youcan'
ttakeanexistingRationalandmodifyitsvalues,sotheonlyalternativeistocreatenewRationalsoutofthevaluesofanexistingone,orcreateitfromscratch.Thisbringsintofocusthenextsetoffourmethods:
thecuriouslynamed+,-,*,and/methods.
Andno,contrarytowhatitmightlooklike,thisisn'
toperator-overloading.
Operator,ringmeanumber
RememberthatinScalaeverythingisanobject.Inthelastarticle,yousawhowthatprincipleappliestotheideathatfunctionsthemselvesareobjects,whichallowsScalaprogrammerstoassignfunctionstovariables,passfunctionsasobjectparameters,andsoon.Anequallyimportantprincipleisthateverythingisafunction;
thatistosay,inthisparticularcase,thereisnodistinctionbetweenafunctionnamedaddandafunctionnamed+.InScala,alloperatorsarefunctionsonaclass.Theyjusthappentohave,well,funkynames.
IntheRationalclass,then,fouroperationshavebeendefinedforrationalnumbers.Thesearethecanonical,mathematicaloperationsadd,subtract,multiply,anddivide.Eachoftheseisnamedbyitsmathematicalsymbol:
+,-,*,and/.
Notice,however,thateachoftheseoperatorsworksbyconstructinganewRationalobjecteachtime.Again,thisisverysimilartohowjava.lang.Stringworks,anditisthedefaultimplementationbecauseityieldsthread-safecode.(Ifnosharedstate--andinternalstateofanobjectsharedacrossthreadsisimplicitlysharedstate--ismodifiedbyathread,thenthereisnoconcernoverconcurrentaccesstothatstate.)
What'
snewwithyou?
Theeverythingisafunctionrulehastwopowerfuleffects:
Thefirst,asyou'
vealreadyseen,isthatfunctionscanbemanipulatedandstoredasobjectsthemselves.Thisleadstopowerfulre-usescenariosliketheoneexploredinthefirstarticleinthisseries.
ThesecondeffectisthatthereisnospecialdistinctionbetweentheoperatorsthattheScala-languagedesignersmightthinktoprovideandtheoperatorsthatScalaprogrammersthinkshouldbeprovided.Forexample,let'
sassumeforamomentthatitmakessensetoprovidean"
inversion"
operator,whichwillflipthenumeratoranddenominatorandreturnanewRational(sothatRational(2,5)willreturnRational(5,2)).Ifyoudecidethatthe~symbolbestrepresentsthisconcept,thenyoucandefineanewmetho
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 计算机专业 外文 翻译 thinkinjava