




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Constructor
MethodConstructormethodisakindofspecialmethod,whichhasthefollowingcharacteristics:
thenameoftheconstructormethodmustbethesameasthenameoftheclassname
theconstructormethodhasnoreturntype,evenincludingvoid
whentheconstructormethod
createsanobject,itusesthenewkeywordtocall
theconstructormethodinitializesanewobject
theconstructormethodwithoutparametersiscallednonparametricconstructormethod
therecanbemorethanoneconstructormethodinaclassProblemMusteveryclasswriteconstructormethod?Ifthereisnoconstructorinaclass,istherenoconstructorforthisclass?ConstructorMethodClasscouldnotwriteconstructormethod.Inthiscase,theclassimplicitlydeclaresanonparametricconstructormethodwhosemethodbodyisempty.Thisconstructormethodiscalledthedefaultconstructormethod.Thedefaultconstructormethodisautomaticallygeneratedonlywhentheconstructormethodisnotexplicitlydeclaredinthisclass.classWelcome{publicstaticvoidmain(String[]args){
System.out.println(“welcometoJava!”);}}
classWelcome{publicstaticvoidmain(String[]args){
System.out.println(“welcometoJava!”);}
publicWelcome(){}}beequaltoTheroleofconstructionmethodsJavausesthekeywordnewtocalltheconstructormethodtocreateobjectandinitializenewobject.
newconstructorname(actualparameter);Theprocessoftheobjectiscreatedisasfollows:(1)Thekeywordnewcreatesanobject,allocatesspacefortheobject,andassignstheinitialvalue(0value)tothemembervariable.(2)Calltheconstructormethodtoinitializethenewobject.(3)Theconstructormethodreturnsareferencetothenewobject,whichcanbeassignedtoavariableofthesametype.CallconstructormethodtocreateobjectclassCircle{ doubleradius; Circle(doubleradius){ this.radius=radius;} doublegetArea(){ returnthis.radius*this.radius*3.14;}}publicclassTest{ publicstaticvoidmain(String[]args){
Circlec1=newCircle(2.5);Circlec2=newCircle(5.0);}}Definemultipleconstructionmethods6publicclassCircle{ doubleradius; Circle(){this.radius=1.0;}Circle(doubleradius){ this.radius=radius;} doublegetArea(){ returnthis.radius*this.radius*3.14;}}publicclassTest{ publicstaticvoidmain(String[]args){
Circlec1=newCircle(2.5);//calltheconstructorthatrequiresadoubleparameter
Circlec2=newCircle();//calltheconstructormethodwithoutparameters}}Twoconstructionmethodsaredefinedinthecircleclass.
Theyhavedifferentparameters,whicharecalledconstructormethodoverloading.Usingobjectaccessthemembervariablesoftheobject:objectreference.membervariablenamemethodofcallingobject:objectreference.methodname(argument)Usingobjects1.radiusvariableisthemembervariableoftheCircleclass.Whenradiusisusedinastatement,itreferstotheradiusofthecurrentobject.2.Whatisthecurrentobject?WhocallsthegetAreamethodisthecurrentobjectofthegetAreamethod.
c1.getArea()c1isthecurrentobjectofgetAreamethod,andtheradiusofc1isusedinthestatementc2.getarea(),c2isthecurrentobjectofgetAreamethod,andtheradiusofc2isusedinthestatementpublicclassCircle{ doubleradius; Circle(doubleradius){this.radius=radius;} doublegetArea(){
returnthis.radius*this.radius*3.14;}}0x34AC00x34AB6c1radius:2.5Circleobjectc2radius:5Circleobjectthis.radiusiscurrentobjectpointstothepointertothepreviousobjectExercise1CreateahumanclasscalledPerson,therequirementsareasfollows:containstwomembervariables:name,ageconstructormethod1:withtwoparameters,assignvaluestonameandagerespectivelyconstructormethod2:with1parameter,onlynameisassignedmethod:voidspeak()Output:Helloeveryone,mynameisXXX.I'mXXyearsold.CreateatestclasscalledTestPerson,therequirementsareasfollows:createapersonobjectwithyourowninformationandcallitsspeakmethodExercise2CreateaclasscalledCar,therequirementsareasfollows:containthreemembervariables:name,priceandspeed,whichrepresentthebrand,priceandspeedofthecarrespectivelyconstructormethod:with3parameters,assignvaluesto3membervariablesrespectivelymethod1:voidspeedup(ints)isusedtoincreasethevehiclespeedtothespecifiedvaluemethod2:voidstop(),stopandreducethespeedto0CreateatestclasscalledTestCar,includingthemainmethod,whichimplementsthefollowingfunctions:createcarObjectc,thevaluesofthreepropertiesareself-definedacceleratecto100andoutputthespeedofcstopcandoutputthespeedofcExercise3CreateaclasscalledPoint,therequirementsareasfollows:containtwomembervariables:xandy,whichrepresenttheabscissaandordinateofthepointrespectivelyaconstructormethod:twoparameters,whichareusedtoassignthespecifiedinitialvaluestothemembervariablesxandymethod:voidmove(intx,inty)isusedtomovethepointtothecoordinatespecifiedbytheparameterCreateatestclassTestPoint,includingthemainmethod,whichimplementsthefollowingfunctions:createpointobjectp1withxcoordinateof2andycoordinateof3,andoutputitsxandycoordinatescreatepointobjectp2withxcoordinateof5andycoordinateof-1,andoutputitsxandycoordinatesmovep2to(0,0)andoutputitsxandycoordinatesExercise4PublicclassRectangle{//rectangleclass
Intwidth;//widthofrectangle
Intheight;//heightofrectangleRectangle(intwidth,intheight){ //supplement } voidmove(intx,inty){ //supplement } intgetArea(){ //supplement }}createatestclass,createaRectangle’sobject,outputitsareaThedefaultvalueofthemembervariablepublicclassTest{publicstaticvoidmain(String[]args){ Circlec=newcircle();//createCircleobjectc
System.out.println(c.getarea());//whatdoesthissentenceoutput?
System.out.println(c.radius);//whatdoesthissentenceoutput?}}publicclassCircle{ doubleradius;
Circle(){}Circle(doubleradius){this.radius=radius;} doublegetArea(){returnthis.radius*this.radius*3.14;}}ThedefaultvalueofthemembervariableWheninstantiatinganobject,themembervariablewillbeautomaticallyassignedinitialvalue:Theinitialvalueofthemembervariableofthereferencetypeisnull.Theinitialvalueofanumericmembervariableis0.Theinitialvalueofthemembervariableofbooleantypeisfalse.Theinitialvalueofthemembervariableofchartypeis'\u0000'.LocalvariableshavenodefaultinitialvaluepublicclassTest{publicstaticvoidmain(String[]args){intx;//xhasnodefaultvalueStringy;//yhasnodefaultvalue
System.out.println("xis"+x);//compilationerror
System.out.println(“yis"+y);//compilationerror}}classCircle{doubleradius;Circle(doubleradius){this.radius=radius;}..}publicclassTest{publicstaticvoidmain(String[]args){Circlec1=newCircle(4);
c1.radius=-5;//Isthisassignmentmeaningful?
Circlec2=newCircle(-3);//Isitmeaningfultocreatesuchacircle?}}Whendesigningaclass,themembervariablesshouldnotbeexposedtotheoutsideworld.Thenusetheassignmentstatementtoassignvaluestothemembervariables.classCircle{
privatedoubleradius;Circle(doubleradius){this.radius=radius;}..}Step1:definethemembervariableasprivatepublicclassTest{publicstaticvoidmain(String[]args){ Circlec1=newCircle(4);
C1.radius=-5;//compilationerror
System.Out.Print(C1.Radius);//compilationerror
}}membersdefinedasprivatecannotbeaccessedoutsidetheclass(read/write)classCircle{privatedoubleradius;publicCircle(doubleradius){if(radius>=0){this.radius=radius;}}publicdoublegetRadius(){returnradius;}publicvoidsetRadius(doubleradius){if(radius>=0){this.radius=radius;}}}Circlec1=newCircle(5);
c1.Setradius(7);//callthesetmethodtoassignvaluestothemembervariablesoftheobject
doubler=c1.getRadius();//callthegetmethodtogetthevalueofamembervariableoftheobjectStep2:Providepublicgetandsetmethodsformembervariablestoaccessvariablevalues.Inthesetmethod,conditionalstatementscanbeusedtoensurethevalidityoftheassignment.GetandsetmethodnamingclassA{privateintabc;publicintgetAbc(){returnabc;}publicvoidsetAbc(intnewAbc){abc=newAbc;}}1.Thegetmethodisnamedget+membervariablename(thefirstletterofthemembervariablenameischangedtouppercase),andthereturntypeisthetypeofthemembervariable.Noparametersarerequired.Themethodreturnsthevalueofthemembervariable.2.Thesetmethodisnamedasset+membervariablename.Thefirstletterofthemembervariablenameischangedtouppercase.Thereturntypeisvoidand1parameter.Thetypeisconsistentwiththetypeofthemembervariabletobemodified.Themethodassignsthevalueofthemembervariableastheparametervalue.ReflectionIfamembervariableisnotallowedtobemodifiedoutsidetheclass,whatmeasuresshouldbetakenwhenwritingtheclass?Ifthevalueofamembervariableisnotallowedtobeaccessed(readorwrite)outsidetheclass,whatmeasuresshouldbetakenwhenwritingtheclass?PracticeChangeallmembervariablesofperson,car,point,rectangleclassesintoprivate,andwritegetandsetmethodsforthem.ObjectmemorymodelJavalanguagedividesdatatypesintotwocategories:Primitivedatatype:byte,short,int,long,float,double,boolean,charReferencetype:class,array,interfacePrimitivedatatypevariablesstoredatavaluesinti=10;intj=12;10i:j:12ObjectmemorymodelThereferencevariablecontainsthereferenceaddressoftheobjectorarray
Personp=newPerson("ZhangSan",18);0x34AC0p:age:name:"ZhangSan"Personobject,memoryaddress0x34ac0Object'sinstancemembervariables(nonstaticvariables)arestoredintheobject'sspace18Replicationofbasicdatatypevariablesinti=2;intj=i;i2j2CopyingofreferencetypevariablesPersonp1=newPerson("ZhangSan",18);Personp2=newPerson("LiSi",20);p1=p2;p1:0x34AB6p2:age:18name:Personobject,memoryaddress0x34ac0"ZhangSan"age:20name:Personobject,memoryaddress0x34ab6"LiSi"Ifanobjecthasnoreferencetoit,itbecomesuseless.Itwillbegarbagecollected,Javavirtualmachineautomaticallyreclaimsuselessobjectsandfreespace.0x34AC00x34AB6Uselessobject,garbageclassA{intx,y;A(inta,intb){x=a;y=b;
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 六一活动捕鱼活动方案
- 六一童心诵读活动方案
- 共享单车促销活动方案
- 共同督促活动方案
- 天津中考历史题库及答案
- 关于协作团辅活动方案
- 关于大众活动方案
- 数字乡村建设推动农村人口流动与劳动力市场重构
- 大学生网络素养的基本内涵与发展趋势分析
- 姻亲管理对家族企业战略变革的影响研究
- 11ZJ311地下室防水图集
- 土地整治实施操作手册
- 深圳市引导基金管理办法
- 10以内连加练习题完整版51
- GB 30254-2024高压三相笼型异步电动机能效限定值及能效等级
- 机场建造行业投资机会与风险识别及应对策略报告
- 统编版语文一年级下册第四单元整体解读
- 重大事故隐患判定标准与相关事故案例培训课件
- 环境检测实验室分析人员绩效考核方案
- (正式版)CB∕T 4548-2024 船舶行业企业相关方安全管理要求
- CJT 166-2014 建设事业集成电路(IC)卡应用技术条件
评论
0/150
提交评论