chiperortiz
chiperortiz

Reputation: 4991

Java>=8 call a default method on interface in a static context with instanceof instance?

I was typing and i wonder how can i call a default method on a static context i have a snippet like this.

interface InterfaceWithDefaultMethod{  
   public default void saySomething(final int a,final int b){System.out.println(String.format("Parameters are %d %d",a,b));}
}
public class StaticsMethodIsNotOverriden2 implements InterfaceWithDefaultMethod {
   public static void main(String[] args) {
      final StaticsMethodIsNotOverriden2 clazz = new StaticsMethodIsNotOverriden2();
      clazz.saySomething(13,20);//Overriden method call with 13 20
      clazz.callDefaultSaySomethingFromInstance();//Parameters are 1 2        
      /*HOW CALL public default void saySomething(final int a,final int b) METHOD HERE....????*/
      clazz.InterfaceWithDefaultMethod.super.saySomething(1, 2);/*no enclosing instance of type InterfaceWithDefaultMethod is in scope*/        
   }    

   @Override
   public void saySomething(int a, int b) {
      System.out.println(String.format("Overriden method call with %d %d",a,b));
   }
   //THIS IS WHAT A WANT TO DO BUT IN STATIC CONTEXT...
   private void callDefaultSaySomethingFromInstance(){
      InterfaceWithDefaultMethod.super.saySomething(1, 2); /*CALLING DEFAULT METHOD FROM INSTANCE CONTEXT*/       
   }
}

Is possible to call the default method of InterfaceWithDefaultMethod->saySomething method from static context using a StaticsMethodIsNotOverriden2 instance??

Sorry if the question is plain.

This is not working.

Upvotes: 1

Views: 488

Answers (1)

ernest_k
ernest_k

Reputation: 45329

No. A default method is an instance method and, in this case, dynamic binding will kick in. There's no construct for a client of an overridden method to force the invocation of the super-implementation. This can only be done from the subclass (as you've done it in callDefaultSaySomethingFromInstance)

Your only option is to expose a different method in the subclass, and make that method call the implemented interface's default method:

class StaticsMethodIsNotOverriden2 implements InterfaceWithDefaultMethod {
    public static void main(String[] args) {
        ...
        clazz.superSaySomething(1, 2);
    }

    //a different name/signature needed
    public void superSaySomething(int a, int b) {
        System.out.println(String.format("Forcing super method call with %d %d", a, b));
        //the subclass calls default method
        InterfaceWithDefaultMethod.super.saySomething(a, b); 

    }

    @Override
    public void saySomething(int a, int b) {
        System.out.println(String.format("Overriden method call with %d %d", a, b));
    }

    ...
}

Upvotes: 5

Related Questions