Java this关键字
1.this可以用来修饰,属性,方法,构造器
2.this修饰属性和方法:
2.1this表示当前对象或当前正在创建的对象
2.2在类的方法和构造器构造中,可以使用this.属性,或this.方法,调用对应的属性或方法,通常情况下可以省略this,当方法的形参和类的属性同名时,需要显式的使用this。
3.this用来调用构造器
3.1在类的构造器中,可以显式的使用this(形参)的方式,调用类中其他构造器.不能调用自己。
3.2构造器内,this(形参)必须声明在构造器的首行,且只能调用一个(this()和super()也只能调用一个)。
3.3构造器之间不能套娃调用。
/*
this关键字(同python self)
1.this可以用来修饰,属性,方法,构造器
2.this修饰属性和方法:
2.1this表示当前对象或当前正在创建的对象
2.2在类的方法和构造器构造中,可以使用this.属性,或this.方法,调用对应的属性或方法,
通常情况下可以省略this,当方法的形参和类的属性同名时,需要显式的使用this
3.this用来调用构造器
3.1在类的构造器中,可以显式的使用this(形参)的方式,调用类中其他构造器.不能调用自己
3.2构造器内,this(形参)必须声明在构造器的首行,且只能调用一个
3.3构造器之间不能套娃调用
*/
package Day3;
public class ThisTest {
public static void main(String[] args){
Person p1 = new Person();
p1.setName("Zane");
System.out.println(p1.getName());//Zane
p1.eat();//Eating
System.out.println("************");
Person p2 = new Person("Yang",22);
System.out.println(p2.getName());//Yang
System.out.println(p2.getAge());//22
}
}
class Person{
private String name;
private int age;
public Person(){
this.eat();//调用类里面的方法
}
public Person(String name){
this();//调用上一个空参构造器
this.name = name;
}
public Person(int age){
this.age = age;
}
public Person(String name, int age){
this(age);//调用含参构造器,同下面this.age = age等效
this.name = name;
//this.age = age;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
//methods
public void eat(){
System.out.println("Eating!");
}
}