资讯中心

this关键字

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