Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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");
    }

}
like image 465
Vinay Avatar asked Nov 14 '25 16:11

Vinay


1 Answers

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!

like image 69
anacron Avatar answered Nov 17 '25 08:11

anacron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!