Java this关键字

成员方法中的this

  指当前类对象

  更准确的说法是指调用该成员方法的对象

public class People {
    String name;
    int age;
    
    //this表示当前类对象,谁调用就指代谁
    public void setNameAndAge() {
        this.name = "李四";
        this.age = 28;        
//        age = 300;//省略了this,最好不要这样写
    }
    
    public void setAge(int age) {
        this.age = age;    //区分了成员变量和局部变量
    }
    
    //使用this调用成员方法
    public void test() {
        this.setAge(100);
    }
}
public class Test {
    public static void main(String[] args) {
        People p = new People();
        System.out.println("姓名:" + p.name + ",年龄:" + p.age);
        p.setNameAndAge();
        System.out.println("姓名:" + p.name + ",年龄:" + p.age);
        p.test();
        System.out.println("姓名:" + p.name + ",年龄:" + p.age);
    }
}

 

this可被当作实例方法或类方法的实参和返回值

public class Dog {
    //类的类型作为参数
    public void eat(Dog d) {
        
    }
    //this作为实参,表示调用该方法的对象
    public void test() {
        System.out.println(this);
        this.eat(this);
    }
    //this作为返回值,表示返回调用该方法的对象
    public int age = 0;
    public Dog sleep() {
        age++;
        return this;
    }
}
public class Test {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.test();
        System.out.println(d);
         
        Dog g1 = new Dog();
        System.out.println(g1);
        Dog g2 = g1.sleep();
        System.out.println(g2);
        System.out.println(g2.age);
        Dog g3 = g1.sleep()
                    .sleep()
                        .sleep();
        System.out.println(g3.age);    
    }
}

 

this还可用于构造方法中

 

posted @ 2017-11-28 08:22  LeeAaron  阅读(258)  评论(0编辑  收藏  举报