this 关键字

this 关键字

this关键字在使用中,代表调用方法的对象本身的引用,指向这个对象。一般在类内部调用方法时,无需添加 this 关键字 可直接调用。因为在编译的时候 编译器会自动给你带上 this 关键字。

在构造器中使用

直接举个栗子:

public class ThisTestDemo {
    String s = "初始值";
    public ThisTestDemo(int i){
        System.out.println("构造器拥有一个int 参数");
    }

    public ThisTestDemo(String s){
        this.s = "改变参数";
        System.out.println("构造器拥有 String 参数, s的值:" + s);
    }

    public ThisTestDemo(){
        this(1);
        //this("s"); //不能在一个构造器里面调用this构造器两次,因为this构造器调用必须放在first statement

    }

    public static void main(String[] args) {
        ThisTestDemo t = new ThisTestDemo();
    }
}

可以发现: this 在构造器里面调用另一个构造器的话 只能调用一次,因为 this在构造器里面使用必须放在第一行。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容