为什么在Java接口中使用此关键字,它指的是什么? [英] why this keyword is used in java interface and what does it refer?

查看:131
本文介绍了为什么在Java接口中使用此关键字,它指的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现可以在interface中使用this关键字.

I just figured that I can use the this keyword in an interface.

那么,如果this关键字表示class中当前的class对象引用,那么它在interface中表示什么?

So, if this keyword represents current class object reference in a class, then what does it represent in an interface?

interface InterfaceOne {

    default void display() {
        this.defaultMethod();
        System.out.println("InterfaceOne method displayed");
    }

    default void defaultMethod() {
        System.out.println("defaultMethod of InterfaceOne called");
    }

}

推荐答案

即使在这种情况下,this关键字也使用相同的上下文和含义.

Even in this case, the this keyword is used in the same context and meaning.

您缺少的一件事是,this关键字表示当前的"Object" 而不是当前的"Class" .因此,如果并且当您创建此接口" 的对象时(当然,通过在另一个类中实现该对象),this关键字将表示该特定对象.

One thing you are missing is, that the this keyword represents the current "Object" and not current "Class". So, if and when you create an object of this "Interface" (by implementing it in another class of course), the this keyword will represent that specific object.

例如,如果有,

class ClassOne implements InterfaceOne{
}

然后,您可以拥有

InterfaceOne one = new ClassOne();

one.display(); // Here, the "this" keyword in your display method, will refer to the object pointed by "one".


希望这会有所帮助!


Hope this helps!

这篇关于为什么在Java接口中使用此关键字,它指的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆