Java this关键字

表示类中属性

class Test {
    private int age;

    public Test(int age) {
        super();
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
};

public class This {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Test t = new Test(10);
        System.out.println(t.getAge());
    }
}

实验现象

10

表示类中方法

class Test {
    private int age;

    public Test() {
        super();
        // TODO Auto-generated constructor stub

        System.out.println("Test here");
    }

    public Test(int age) {
        this();
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
};

public class This {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Test t = new Test(10);
        System.out.println(t.getAge());
    }
}

实验现象

Test here
10

表示当前对象

class Test {
    private int age;

    public Test() {
        super();
        // TODO Auto-generated constructor stub

        System.out.println(this);
    }
};

public class This {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println(new Test());
    }
}

实验现象

hello.Test@7852e922
hello.Test@7852e922
posted @ 2018-06-11 13:33  thomas_blog  阅读(86)  评论(0编辑  收藏  举报