Vin*_*nay 3 java interface this keyword java-8
我只是想我可以this在interface.
那么,如果this关键字class在 a 中代表当前对象引用class,那么它在 a中代表什么interface?
interface InterfaceOne {
default void display() {
this.defaultMethod();
System.out.println("InterfaceOne method displayed");
}
default void defaultMethod() {
System.out.println("defaultMethod of InterfaceOne called");
}
}
Run Code Online (Sandbox Code Playgroud)
即使在这种情况下,this关键字也用于相同的上下文和含义。
您缺少的一件事是,this关键字表示当前的"Object"而不是当前的"Class"。因此,如果并且当您创建此“接口”的对象时(当然是通过在另一个类中实现它),this关键字将代表该特定对象。
例如,如果你有,
class ClassOne implements InterfaceOne{
}
Run Code Online (Sandbox Code Playgroud)
那么,你可以拥有,
InterfaceOne one = new ClassOne();
one.display(); // Here, the "this" keyword in your display method, will refer to the object pointed by "one".
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!