2

If I have a class which has an interface definition like below;

public class FirstClass {

  private static onDragListener listener  

  public interface onDragListener{
      void doSomething();
  }

  //a static method to set on my drag listener
  public static void setOnDragListener(onDragListener listener){
           FirstClass.listener = listener
  }

}

As you see above, there is a setOnDragListener(onDragListener listener) static method to set on the listener.

Then, there is another class which implements the interface defined in the first class like below:

public class SecondClass implements onDragListener{
    public void initialize(){
          FirstClass.setOnDragListener(this); //my question is here about 'this'. 
    }
}

My question is why I can use this as the argument pass to the FirstClass.setOnDragListener(this); in the initialize() method above?

I mean the setOnDragListener(onDragListener listener) is expecting a onDragListener type argument to pass in, does this in the initialize method of second class means the real implementation of the interface or how can I understand it?

4 Answers 4

3

Inheritance is a is-a relationship.

SecondClass is-a onDragListener.

this is a SecondClass.

Ergo, this is a onDragListener.

0

In this situation you're refering to the object itself which will be implementing the onDragListener.

0

setOnDragListener() expects an onDragListener interface to be passed as argument. SecondClass implements onDragListener interface, so you can pass this from a SecondClass instance to FirstClass.setOnDragListener(), because this implements onDragListener

0

As your SecondClass implements the onDragListener interface it can be used anywhere an onDragListener is needed because it is an onDragListener.

The 'this' in the call to FirstClass.setOnDragListener(this) is the current instance of SecondClass which is an onDragListener.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.