为什么在java接口中使用这个关键字?它指的是什么?

为什么在java接口中使用这个关键字?它指的是什么?,java,interface,java-8,this,keyword,Java,Interface,Java 8,This,Keyword,我只是想我可以在界面中使用this关键字 那么,如果这个关键字表示类中当前的类对象引用,那么它在接口中代表什么呢 interface InterfaceOne { default void display() { this.defaultMethod(); System.out.println("InterfaceOne method displayed"); } default void defaultMethod() {

我只是想我可以在
界面中使用
this
关键字

那么,如果
这个
关键字表示
中当前的
对象引用,那么它在
接口
中代表什么呢

interface InterfaceOne {

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

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

}

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

您缺少的一点是,
this
关键字表示当前的“对象”,而不是当前的“类”。因此,如果您创建这个“接口”的对象(当然是通过在另一个类中实现它),那么
this
关键字将表示该特定对象

例如,如果你有

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".

希望这有帮助

“this”表示实现接口的新实例

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

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

public class TestImp implements InterfaceTest {

    @Override
    public void defaultMethod() {
        System.out.println("xxxx");
    }
}

public class Test {
    public static void main(String args[]) {
        TestImp imp=new TestImp();
        imp.display();
    }
}

//console print out:
xxxx
InterfaceOne method displayed

当前的
对象
实例在其当前引用的范围内。在此处使用
与在普通
中一样过时。如果您只编写
defaultMethod()
,而不使用过时的
this
,那么思考会发生什么可能会有所帮助。然后考虑在编写<代码>时没有发生任何变化。< /代码>只需添加,<代码> > <代码>的唯一例外是调用另一个构造函数内的重载构造函数。但在这个问题中,上下文是使用
this
作为自参考指针。这就是为什么我说同样的上下文和意思。