Reputation: 197
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");
}
}
Upvotes: 4
Views: 4675
Reputation: 127
"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
Upvotes: 1
Reputation: 6721
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!
Upvotes: 6