第十八天
学到了this关键字的使用方法
明天打算学习“包”
this指的是当前对象,至于是哪一个对象,只有在运行期才能知道具体是哪一个对象。
在Java中用户可以通过this关键字来访问类中的属性、方法。
1、this关键字访问属性
public class ThisDemo { int x=5; public ThisDemo() { System.out.println(this.x); System.out.println(x); } public static void main(String[] args) { ThisDemo demo=new ThisDemo(); } }
2、通常this关键字与构造器结合使用
public class ThisDemo { int x=5; public ThisDemo(int x) { //this.x指的是属性x //方法传入的x,指的是形参x this.x=x; } public static void main(String[] args) { ThisDemo demo=new ThisDemo(9); System.out.println(demo.x); } }
3、通过构造器可以给属性传值,以及初始化属性值。
(1)调用方法
public class ThisDemo { public static void main(String[] args) { ThisDemo th=new ThisDemo(); th.t(); th.t2(); th.t3(); } public void t() { System.out.println("t"); } public void t2() { t(); } public void t3() { this.t(); } }
(2)调用无参构造方法
public class ThisDemo { int x; public ThisDemo() { System.out.println("无参构造函数"); } public ThisDemo(int x) { this(); this.x=x; } public static void main(String[] args) { ThisDemo th=new ThisDemo(9); }

this()是指调用本类中的无参数构造器
(3)调用有参数构造方法
public class ThisDemo {
int x;
public ThisDemo() {
System.out.println("无参构造函数");
}
public ThisDemo(int x) {
this.x=x;
System.out.println(x);
}
public ThisDemo(int x,int y) {
this(x);
y=20;
}
public static void main(String[] args) {
ThisDemo th=new ThisDemo(9,7);
ThisDemo tha=new ThisDemo();
}
}
this(x)是指调用本类中的有参构造器,可以将()看成是方法,如果this什么都不写,就是调用的是本类中的无参构造方法,如果里面有参数,则是调用本类中的有参构造器,一个参数则是调用本类中带一个参数的构造器,多个参数则是调用多个参数的构造器。
***使用this调用构造器时,this关键字必须当在构造器的第一行否则会报错。