1、this是一个对象,代表调用该函数的对象;
类内访问成员变量 this.成员变量,一般情况是可以省略;当成员变量和函数参数名相同时,必须使用this;
Person(String name,int age){
this.name=name;
this.age=age;
System.out.println("两个参数的构造函数!");
}
2、构造函数中赋值使用this;
this调用参数相匹配的构造函数;this();this(name,age);在构造函数中this()要在第一行;
class Person{
String name;
String address;
int age;
Person(){
System.out.println("无参数的构造函数!");
}
Person(String name,int age){
this.name=name;
this.age=age;
System.out.println("两个参数的构造函数!");
}
Person(String name,int age,String address){
this(name,age);
this.address=address;
System.out.println("三个参数的构造函数!");
}
void talk(){
System.out.println("My name is:"+name);
}
}
总结:
1) this 关键字是类内部当中对自己的一个引用,方便类中方法访问自己的属性;
2)可以返回对象的自己这个类的引用,同时还可以在一个构造函数当中调用另一个构造函数