5

Why when in interface, calling static interface method from default interface method I cannot use this.staticInterfaceMethod(), while when in regular class, calling static class method from instance method it is perfectly valid to use this.staticClassMethod() (though it is bad style)?

At the same time, it is perfectly valid to use this within default methods of interface - I can legally do the following:

interface I {   
    int MY_CONST = 7;   
    static void st_f() {}       
    default void f1() {}

    default void f_demo() {
        this.f1();                  // fine!
        int locvar = this.MY_CONST; // also fine! 

        this.st_f(); // c.ERR:  static method of interface I can only be accessed as I.st_f 
    }
}
Code Complete
  • 3,146
  • 1
  • 15
  • 38
  • 4
    Your answer is here: https://stackoverflow.com/questions/34709082/illegal-static-interface-method-call/34709162. See Brian Goetz's comment "We consider the ability to invoke a static method through an instance to be a language design error, unfortunately one which we can't fix retroactively for classes. We could at least not make the same mistake [with interfaces]" – Vasan Feb 01 '18 at 21:25

1 Answers1

4

"Static method may be invoked on containing interface class only."

Static methods are not inherited from an interface by the class that implements the interface (§8.4.8). The this keyword refers to the current object, hence attempting to invoke this.staticInterfaceMethod() would imply that somehow an Object exists that has inherited the static interface method. This cannot happen; interfaces cannot be instantiated by themselves and any implementation of the interface did not inherit the static method. Thus, this.staticInterfaceMethod() does not exist so you would need to invoke the method on the Interface itself.

A simplified explanation as to why you don't inherit the static method is the following scenario:

public interface InterfaceA {
    public static void staticInterfaceMethod() {
        ...
    }
}

public interface InterfaceB {
    public static void staticInterfaceMethod() {
        ...
    }
}

public class ClassAB implements InterfaceA, InterfaceB {
    ...
}

What static method would ClassAB inherit? The two static methods have the same signature and thus would be unidentifiable on a call; neither would hide the other.

At the same time, it is perfectly valid to use this within default methods of interface.

Using the this keyword to reference default methods, variables and etc is permitted as every Object that can exist that inherits from the interface will inherit these properties.

Zachary
  • 1,693
  • 1
  • 9
  • 13