Java基础--this关键字

1、使用在类中,可以用来修饰属性、方法、构造器

2、表示当前对象或者当前正在创建的对象

3、当形参与成员变量重名时,如果在方法内部需要使用成员变量,必须添加this来标明该变量时类成员

4、在任意方法内,如果使用当前类的成员变量或者成员方法可以在其前面添加this,增强程序的阅读性

5、在构造器中使用“this(形参列表)”显式的调用本类中重载的其他的构造器
5.1 要求this(形参列表)要声明在构造器的首行
5.2 类中若存在n个构造器,那么最多有n-1构造器中使用了this

public class thiskey {
     public static void main(String[] arg){
         Person p1=new Person();
         System.out.println(p1.getName()+":"+p1.getAge());
         Person p2=new Person("BB",23);
         int temp=p2.compare(p1);
         System.out.println(temp);
     }
}

class Person{
    private String name;
    private int age;
    //构造器中使用
    public Person(){
        this.name="AA";
        this.age=1;
    }

    public Person(String name){
        this();
        this.name=name;
    }
    //在构造器中使用“this(形参列表)”显式的调用本类中重载的其他的构造器
    public Person(String name,int age){
        this(name);
        this.age=age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }
   //形参与成员变量重名时,如果在方法内部需要使用成员变量,必须添加this来标明该变量时类成员
    public void setAge(int age) {
        this.age = age;
    }

    public void eat(){
        System.out.println("eating");
    }
    public void sleep(){
        System.out.println("sleeping");
        this.eat();
    }
    //比较当前对象与形参的对象的age谁大
    public int compare(Person p){
        if(this.age>p.age)
            return 1;
        else if(this.age<p.age)
            return -1;
        else
            return 0;
    }
}

猜你喜欢

转载自blog.csdn.net/wxr15732623310/article/details/80471684