why this keyword is used in java interface and what does it refer?

空扰寡人 提交于 2019-12-08 05:38:46

问题


I just figured that I can use the this keyword in an 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");
    }

}

回答1:


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

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.

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!




回答2:


"this" represents the new Instance which implements the interface

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


来源:https://stackoverflow.com/questions/42780642/why-this-keyword-is-used-in-java-interface-and-what-does-it-refer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!