this关键字
文章目录
- 有个规定:
有个规定:
在一个类中,声明了n个构造器,则最多有n-1个构造器,可以有“this(形参列表)”的结构,
this(形参列表),必须放在当前构造器的第一行
classPerson{privatedoublebase;// 普通方法(非构造器方法)里的this,就是new出来的那个对象publicdoublegetBase(){returnthis.base;}publicvoidsetBase(doubleb){this.base=b}// 构造器中的this,是,当前正在new过程中的对象(其实也就是你正在new的这个对象)// 无参的构造器publicPerson(){}// 有参的构造器publicPerson(doubleb){this()// 这个this(),作用是,调用无参的构造器this.base=b;}// 有参的构造器publicPerson(doubleb,doubleh){this(b)// 这个this(b),作用是,调用上面那个只有一个形参的的构造器this.base=b;this.height=h;}}publicclassPersonTest(){publicstaticvoidmain(String[]args){// 使用无参的构造器Personp1=newPerson()p1.setBase(10)// 使用有参的构造器Personp2=newPerson(20,30)sout('base='+p2.getBase())}}