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

你离开我真会死。 提交于 2019-12-06 15:49:28

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!

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