![Chapter 2 Java Basic第二章Java基礎(chǔ)知識_第1頁](http://file4.renrendoc.com/view4/M01/36/3B/wKhkGGYo9o2ALxmGAABsjGjRV2g585.jpg)
![Chapter 2 Java Basic第二章Java基礎(chǔ)知識_第2頁](http://file4.renrendoc.com/view4/M01/36/3B/wKhkGGYo9o2ALxmGAABsjGjRV2g5852.jpg)
![Chapter 2 Java Basic第二章Java基礎(chǔ)知識_第3頁](http://file4.renrendoc.com/view4/M01/36/3B/wKhkGGYo9o2ALxmGAABsjGjRV2g5853.jpg)
![Chapter 2 Java Basic第二章Java基礎(chǔ)知識_第4頁](http://file4.renrendoc.com/view4/M01/36/3B/wKhkGGYo9o2ALxmGAABsjGjRV2g5854.jpg)
![Chapter 2 Java Basic第二章Java基礎(chǔ)知識_第5頁](http://file4.renrendoc.com/view4/M01/36/3B/wKhkGGYo9o2ALxmGAABsjGjRV2g5855.jpg)
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
Chapter2
JavaBasicOutline1.DefiningofClasses2.Constructors(構(gòu)造函數(shù))3.The"this"Keyword4.The"static"Keyword5.LifetimesofVariables(變量的生存期)6.PrimitiveTypes(基本類型)7.Conditionals8.ObjectsANDMethods31.DefiningClassesFieldsarevariablesstoredinobjects.Fieldsareusedtostoredata.DifferencebetweenFieldsandMethods?Fieldsneverhaveparameters,andnoparentheses(圓括號)appearafterthem.
Methodsperformactionsontheobjects.41.DefiningClasses
AclassdefinitionfortheHumanclass.classHuman{ publicintage;//TheHuman’sage(aninteger). publicStringname;//TheHuman’sname. publicvoidintroduce() { System.out.println("I’m"+name+“andI’m"+age+“yearsold."); }}51.DefiningClassesHumankayla=newHuman();//Createkayla.kayla.age=12;//Setkayla’sfields.="Kayla";61.DefiningClasses
Question:What’stheoutput?roduce();//Havekaylaintroduceherself.Theoutputis:I’mKaylaandI’m12yearsold.71.DefiningClasses
Ifwewanttomixtwoormoreobjects,wecanclassHuman{ //IncludeallthestufffromthepreviousdefinitionofHumanhere. //… publicvoidcopy(Humanoriginal) { age=original.age; name=; }}82.Constructors(構(gòu)造函數(shù))
CodetoinitializeanewobjectclassHuman{ //Includeallthestufffromthepreviousdefinitionshere. publicHuman(StringgivenName)//samenameasclass { age=12; name=givenName; }}What’sthereturnobjectofcontructors?2.Constructorskayla’snewcoming-outpartytoHumankayla=newHuman("Kayla");roduce();
IfyouwriteyourownHumanconstructor,evenifittakesparameters,thedefaultconstructorgoesaway.Ifyouwanttohavethedefaultconstructorandanotherconstructor,youmustdefinebothexplicitly(顯式).2.ConstructorsOverridethedefaultconstructorclassHuman{ //Includeallthestufffromthepreviousdefinitionshere. publicHuman() { age=0; name="Untitled"; }}3.The"this"KeywordUse“this”indefaultconstructorclassHuman{ //Includeallthestufffromthepreviousdefinitionshere. publicHuman() { this.age=0; ="Untitled"; }}Inthiscase,“this”isoptional(選填項).反義詞:Compulsory必選的3.The"this"KeywordUse“this”inanothermethodpublicvoidchange(intage){ Stringname="Chang";//nameisalocalvariable this.age=age; =name; //use“this”torefertoobject’sfields}Iftheparametersorlocalvariablesofamethodhavethesamenameasthefieldsofanobject,thentheformerhavepriority,andthe"this“keywordisneededtorefertotheobject’sfields.3.The"this"KeywordExecutionofchange()methodkaylathis12agenameKayla8agenameChangParameters&localvariablesofchange()Beforekaylathis8agenameKayla8agenameChangParameters&localvariablesofchange()After3.The"this"KeywordYouCANNOTchangethevalueof"this"!Suchas“this=kayla”What’stheresultofthismistake?Acompile-timeerror.4.The"static"Keyword
Astaticfieldisasinglevariablesharedbyawholeclassofobjects;itsvaluedoesnotvaryfromobjecttoobject.Objectvariablesorstaticfields(classvariables)?HowcouldwecountthenumberofHumanobjects?4.The"static"Keyword
AgoodsolutionclassHuman{ publicstaticintnumberOfHumans; publicintage; publicStringname; publicHuman() { numberOfHumans++;//Theconstructorincrements //thenumberbyone. }}intkids=Human.numberOfHumans/4;//Good.intkids=kayla.numberOfHumans/4;//Thisworkstoo,buthasnothingto//dowithkaylaspecifically.Don’tdothis;it’sbad(confusing)style.4.The"static"Keyword
MethodscanbestatictooclassHuman{ ... publicstaticvoidprintHumans() { System.out.println(numberOfHumans); }}Inastaticmethod,THEREISNO"this"!5.LifetimesofVariables(變量)-Alocalvariable(declaredinamethod)isgoneforeverassoonasthemethodinwhichit’sdeclaredfinishesexecuting.(Ifitreferencesanobject,theobjectmightcontinuetoexist,though.)-Aninstancevariable(non-staticfield)lastsaslongastheobjectexists.-Anobjectlastsaslongasthere’sareferencetoit.-Aclassvariable(staticfield)lastsaslongastheprogramruns.6.PRIMITIVETYPES
Notallvariablesarereferencestoobjects.Somevariablesareprimitivetypes.byte8-bit-128…127Rangeshort16-bit-32768…32767…..int32-bit-2147483648…2147483647…..long64-bit
-9223372036854775808...9223372036854775807…..6.PRIMITIVETYPES
double64-bitRangefloat32-bit±3.40282347E+38(6~7significantdigits)…..boolean1-bittrueorfalsechar16-bit
UnicodeCharacterSet…..±1.79769313486231570E+308(15significantdigits)…..6.PRIMITIVETYPES
DifferencebetweenObjecttypesandPrimitivetypesObjecttypes
PrimitivetypesVariablecontainsareferencevalueHowdefined?classdefinitionbuiltintoJavaHowcreated?"new""6","3.4","true"Howinitialized?constructordefault(usuallyzero)Howused?methodsoperators("+","*",etc.)6.PRIMITIVETYPES
Operationsonint,long,short,andbytetypes.-xx*yx+yx/y<--roundstowardzero(dropstheremainder).x-yx%y<--calculatestheremainderofx/y.Exceptfor“%”,theseoperationsarealsoavailable(適用于)fordoublesandfloats.6.PRIMITIVETYPES
Moreoperationsinjava.langlibrary-theMathclass.x=Math.abs(y);//Absolutevalue.AlsoseeMath.sqrt,Math.sin,etc.-theIntegerclass.intx=Integer.parseInt("1984");//Convertastringtoanumber.-theDoubleclass.doubled=Double.parseDouble("3.14");6.PRIMITIVETYPES
Convertingtypes:integerscanbeassignedtovariablesoflongertypes.inti=43;longk=43L;k=i;//Okay,becauselongsareasupersetofints.i=k;//CompilerERROR.i=(int)k;//Okay.Thestring“(int)”iscalledacast(轉(zhuǎn)換),anditcaststhelongintoanint.Integerscanbedirectlyassignedtofloating-pointvariables,butthereverserequiresacast.7.CONDITIONALS
An“if”statementusesabooleanexpressiontodecidewhethertoexecuteasetofstatements.Theformsare:Form1if(boolValue){ statements;}Form1if(boolValue){ statements1;}else{
statements2;}Form2Form3if(boolValue1){ statements1;}elseif(boolValue2){
statements2;}else{ statements3;}Clausescanbenested(嵌套)anddaisy-chained(多路選擇)8.OBJECTSANDMETHODS
Strings1;//Step1:declareaStringvariable.s1=newString();//Step2:assignitavalue:anewemptystring.Strings2=newString();//Steps1&2combined.s1〝〞s2〝〞Weget…s1="Yow!";//ConstructanewString;makes1areferencetoit.s2=s1;//Assigns2thevalueofs1.s1Yow!s2Whatifwewanttohaveacopyoftheobject?8.OBJECTSANDMETHODS
s2=newString(s1);//Constructacopyofs1;makes2areferencetoit.s1Yow!s2Yow!Theyrefertotwodifferent,butidentical,objects.8.OBJECTSANDMETHODS
s2=newString(s1);//Constructacopyofs1;makes2areferencetoit.s1Yow!s2Yow!-Javalooksinsidethevariables1toseewhereit’spointing.-JavafollowsthepointertotheStringobject.-JavareadsatthecharactersstoredinthatStringobject.-JavacreatesanewStringobjectthatstoresacopyofthosecharacters.-Javamakess2referencethenewStringobject.WhathappenedwhenJavaexecutesthatline?ThreeStringconstructors:8.OBJECTSANDMETHODS
(1)newString()constructsanemptystring,it’sastring,butitcontainsnocharacters.(2)"cs4"constructsastringcontainingthecharacters"cs4".(3)newString(s1)
takesaparameters1.Thenitmakesacopyoftheobjectthats1references.SomeothermethodsofStrings2=s1.toUppercase();//Createastringlikes1,butinalluppercase.Strings3=s2.concat("!!");//Alsowritten:s3=s2+"!!";Strings4="*".concat(s2).concat("*");//Alsowritten:s4="*"+s1+"*";s2YOW!s3YOW!!!s4*YOW!*8.OBJECTSANDMETHODS
Animportantfact:WhenJavaexecutedthelines2=s1.toUppercase();theStringobject"Yow!“didnotchange.Instead,s2itselfchangedtoreferenceanewobject.s1Yow!Stringsareimmutable(無法更改)8.OBJECTSANDMETHODS
Oncethey’vebeenconstructed,theircontents(內(nèi)容)neverchange.IfyouwanttochangeaStringobje
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 一年級上冊數(shù)學(xué)教案-七 加與減(二)第7課時練習(xí)三∣北師大版
- 中國PE靜電保護膜項目投資可行性研究報告
- 宿管會申請書800字
- 2025年注冊會計師責(zé)任保險協(xié)議
- 壓制薄板項目可行性研究報告
- 現(xiàn)代社交媒體在滋補品市場的發(fā)展趨勢
- 【可行性報告】2025年高壓無功補償裝置相關(guān)行業(yè)可行性分析報告
- 一年級上冊數(shù)學(xué)教案-1 得數(shù)在5以內(nèi)的加法 ︳西師大版
- 2025年影視服務(wù)合同電視劇聘請韓國演員中韓文版
- 2025年中國社區(qū)團購行業(yè)市場調(diào)研及未來發(fā)展趨勢預(yù)測報告
- 變電站模塊化建設(shè)2.0版技術(shù)導(dǎo)則
- 無人機飛行表演合同
- 廣州市2023年中考:《道德法治》考試真題與參考答案
- 爺爺?shù)臓敔斈睦飦恚喝祟惼鹪吹难莼^程
- 欒川光伏扶貧發(fā)電項目部qc成果
- 道路硬化施工方案
- 2023年中國職業(yè)教育行業(yè)市場運行態(tài)勢、產(chǎn)業(yè)鏈全景及發(fā)展趨勢報告
- DB4420-T 7-2021 養(yǎng)老機構(gòu)突發(fā)傳染病疫情防控規(guī)范
- 四年級上冊100道口算題大全(通用版各類)
- 食品安全蔬菜水果
- 高中英語課外閱讀:STRANGE CASE OF DR.化身博士
評論
0/150
提交評論