java this关键字用来返回当前类的实例

可以从方法中 this 关键字作为语句返回。 在这种情况下,方法的返回类型必须是类类型(非原始)。 看看下面的一个例子:(更多教程请阅读码农之家)

作为语句返回的语法

return_type method_name(){  
    return this;  
}

从方法中返回为语句的 this 关键字的示例

class A {
    A getA() {
        return this;
    }

    void msg() {
        System.out.println("Hello java");
    }
}

class Test1 {
    public static void main(String args[]) {
        new A().getA().msg();
    }
}

执行上面代码输出结果如下 -

Hello java

验证 this 关键字

现在来验证 this 关键字引用当前类的实例变量。 在这个程序中将打印参考变量,这两个变量的输出是相同的。

class A5 {
    void m() {
        System.out.println(this);// prints same reference ID
    }

    public static void main(String args[]) {
        A5 obj = new A5();
        System.out.println(obj);// prints the reference ID
        obj.m();
    }
}

执行上面代码输出结果如下 -

A5@22b3ea59
A5@22b3ea59
posted @ 2021-12-14 09:44  small_123  阅读(221)  评论(0编辑  收藏  举报