本文最后更新于:1 年前

this 关键字

三个形式上的用途,但本质上就两个:

  • 调用重载的其他构造方法:放置在构造方法体首行的this()或this(实参列表)
  • 作为当前对象,引用成员(数据、方法等):区分同名变量等
  • 作为当前对象,方法返回当前对象的引用,形成链式调用

案 例 :

public class ThisDemo { 
    private int a = 1; 
    private String name = "good"; 
    private int i = 0; 
    public ThisDemo(){ 
        System.out.println("无参构造子" + this); 
    } 
    public ThisDemo(int a, String name){ 
        this(); // 【1】调用无参构造子 
        this.a = a; // 【2】当前对象,引用成员 
        this.name = name; 
    } 
    public ThisDemo setA(int a){ 
        this.a = a; 
        return this; // 【3】返回当前对象 
    }
    public ThisDemo setName(String name){
        this.name = name;
        return this;
    }
    public ThisDemo inc(){
    	i++;
   	 return this;
    }
    public static void main(String[] args) {
        ThisDemo t1 = new ThisDemo();
        t1.setA(100).setName("guo").inc().inc();
        System.out.println(t1.i);
        ThisDemo t2 = new ThisDemo(2, "Tom");
        t2.inc().setA(8).inc().inc(); //【4】链式调用
        System.out.println(t2.i);
    }
}

特别注意,案例中的【3】和【4】。


注:前面的几篇Java笔记中也有提到this,后来上课老师再小结this关键词,结合前面的笔记食用效果更佳。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!

Java笔记—static关键字 上一篇
对SQL的触发器的浅理解 下一篇

 目录