Java this关键字

112 阅读1分钟

this 关键字指向当前类的对象,用this可以访问或调用当前类的各种参数和方法。

再Java语言中,规定使用this关键字来代表本类对象的引用,this关键字被隐式地用于引用对象的成员变量和方法。

public class Test {
    public static void main(String[] args) {
        
        // create an instance of Book called aa
        Book aa = new Book("AA");
        
        // create an instance of Book called bb
        Book bb = new Book("BB");
        
        // Returns its name from a related object
        System.out.println(aa.getName());
        System.out.println(bb.getName());

        Book book = aa.getBook();
        System.out.println(book == aa); // true
    }
}

class Book{
    private String name;
    Book(String name) {
        this.name = name;
    }

    String getName() {return this.name;}

    Book getBook(){return this;}
}