[英]why this keyword is used in java interface and what does it refer?
I just figured that I can use the this
keyword in an interface
. 我只是想知道可以在interface
使用this
关键字。
So, if this
keyword represents current class
object reference in a class
, then what does it represent in an interface
? 因此,如果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");
}
}
Even in this case, the this
keyword is used in the same context and meaning. 即使在这种情况下, this
关键字也会在相同的上下文和含义中使用。
One thing you are missing is, that the this
keyword represents the current "Object" and not current "Class" . 您缺少的一件事是, this
关键字表示当前的“ Object”而不是当前的“ 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. 因此,如果并且当您创建此“接口”的对象时(当然通过在另一个类中实现它),则this
关键字将表示该特定对象。
For example, if you have, 例如,如果您有,
class ClassOne implements InterfaceOne{
}
Then, you can have, 然后,您可以拥有
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! 希望这可以帮助!
"this" represents the new Instance which implements the interface “ 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.