我只是想我可以在 interface
中使用 this
关键字。
所以,如果 this
关键字表示 class
中的当前 class
对象引用,那么它在 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
关键字也用于相同的上下文和含义。
您缺少的一件事是,this
关键字表示当前的“对象” 而不是当前的“类”。因此,如果您创建此“接口(interface)” 的对象(当然是通过在另一个类中实现它),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".
希望这对您有所帮助!
关于java - 为什么在 java 接口(interface)中使用 this 关键字,它指的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42780642/