Master Qiao
Master Qiao

Reputation: 335

what does the keyword this refer to in a default method of an interface in java?

I tested the following programms and the result is weird to me where I think it should be A.

interface O{
   default O get(){
      return this;
   }
}


class A implements O{
   public O get(){
     return O.super.get();
   }
}


 class B extends A{
    public O get(){
       return super.get();
    } 
 }


new B().get().getClass().getName() == B

Upvotes: 2

Views: 1321

Answers (3)

Dmitry.M
Dmitry.M

Reputation: 2972

Default methods of interface can refer to the instance of a class that implements the interface using this keyword:

package test;
public class ThisInterface {
    public static void main(String[] args) {
           A1 c1 = new C1();
           A1 c2 = new C2();
           c1.printCurrentClassName();
           c2.printCurrentClassName();
    }
}

interface A1 {
    default void printCurrentClassName() {
        System.out.println("Current Class Name  = " + this.getClass().getName());
    }
}

class C1 implements A1 {}
class C2 implements A1 {}

the code prints:

Current Class Name  = test.C1
Current Class Name  = test.C2

Upvotes: 0

Bedir Yilmaz
Bedir Yilmaz

Reputation: 4083

This means "Intance of the class that implements this interface." in this case.

Upvotes: 1

Axel
Axel

Reputation: 14169

I wonder how you run this syntactically wrong code?

But to answer your question, this is just a reference to an object, and the actual class of an object does not change just because you return this from a super class. If the object is B (and not something derived from B), then this.getClass() will always be B.class.

PS: Please don't compare strings with ==.

Upvotes: 0

Related Questions