Chapter 2 Java Basic第二章Java基礎(chǔ)知識_第1頁
Chapter 2 Java Basic第二章Java基礎(chǔ)知識_第2頁
Chapter 2 Java Basic第二章Java基礎(chǔ)知識_第3頁
Chapter 2 Java Basic第二章Java基礎(chǔ)知識_第4頁
Chapter 2 Java Basic第二章Java基礎(chǔ)知識_第5頁
已閱讀5頁,還剩29頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(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)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論