this关键字
this关键字是代表当前对象的引用(地址)
public class Person{//(1)类名
//(2)属性
String name;
int age;
String gender;
public Person(){
System.out.println("this="+this);
}
//(3)行为
public void eat(String content){
System.out.println(name+"在吃"+content);
}
public void introduce(){
System.out.println(name+"\t"+age+"\t"+gender);
}
}
this关键字的作用:
- 使用本类的属性(this.name)this可以省略不写
- 使用本类的方法(this.eat())this可以省略不写
- 调用本类的其他构造方法this(),this(…),要求是构造方法中的第一行代码
- 用于区分成员变量和局部变量 this代表成员变量
this关键字在创建对象时,永远指的是当前对象,在调用成员方法时,永远指得是调用该方法的对象
public class Person{//(1)类名
//(2)属性
String name;
int age;
String gender;
public Person(){
System.out.println("this="+this);
}
/*public static void fun(){ //static的方法中不能使用this
System.out.println("this="+this);
}*/
/**方法定义处的参数为形参,方法调用处的参数为实参*/
public Person(String name,int age,String gender){
this(name,age); //调用本类的基它构造方法,要求必须是构造方法中第一句代码
this.gender=gender; //this关键字用于成员变量和局部变量
}
public Person(String name,int age){
this();//调用本类的无参构造方法
this.name=name;
this.age=age;
}
//(3)行为
public void eat(String content){
System.out.println(name+"在吃"+content);
}
public void introduce(){
this.eat("MLT"); //调用本类中的其它成员方法 this可以省略不写
eat("HG");//省略了this
System.out.println(name+"\t"+age+"\t"+this.gender); //调用类的属性this也可以省略不写
}
}
public class Test5 {
public static void main(String[] args) {
Person p1=new Person();//在创建对象时this指代的是p1
Person p2=new Person();//在创建对象时this指代的是p2
System.out.println(p1);
System.out.println(p2);
//在进行方法调用时,永远指代的是调用该方法的对象
p1.introduce(); //this指代的是p1
p2.introduce();//this指代的是p2
}
}