Java中this关键字的认识
this关键字的三种用法
一,this修饰属性
this修饰成员变量,表示直接使用类中的成员变量
例如:
class Person{
private String name;
private int age;
public Person(String name,int age){
this.name = name;//this修饰属性
this.age = age;
}
}
二,this修饰方法
1,this调用类中的成员方法
例如:
class Person{
private String name;
private int age;
public void fun(){
int a = 10;
this.sun();//this调用成员方法
sun();//默认会加上this
}
public void sun(){
//调用属性,默认在属性前面加this
System.out.println("hahaha");
}
}
2,this调用构造方法
(1)语法
this(构造方法参数列表)
(2)当在构造方法中调用其他构造方法时,此时语句写在构造方法的首行
例如:
class Person{
private String name;
private int age; //属性
private int sex;
public Person(){ //无参构造方法
System.out.println("haha")
}
public Person(String name,int age){
this(); //this调用无参构造方法
this.name = name;//this修饰属性
}
public Person(String name,int age,int sex){
this(name,age); //this调用两个参数构造方法
this.sex = sex;//this修饰属性
}
}
3,构造方法调用是线性的,不能是环
三,this表示当前对象的引用
例如:
class Person{
private String name;//属性
private int age;
public void fun(){
//this表示当前对象的引用
System.out.println(this);
}
}
public class Test{
public static void main(String[] args){
Person p1 = new Person();//对象p1
System.out.println(p1);
p1.fun();//this 表示对象p1的引用
Person p2 = new Person();//对象p2
System.out.println(p2);
p2.fun();//this 表示对象p2的引用
}
}