Why can't I access static methods of an interface using an instance variable

Viewed 1930

Why can't I access static methods of an interface using an instance variable.

public class TestClass {
    public static void main(String[] args) {
        AWD a = new Car();
        a.isRearWheelDrive(); //doesn't compile
    }
}

interface AWD {
    static boolean isRearWheelDrive() {
        return false;
    }  
}

class Car implements AWD {
}
2 Answers

This is specified in The Java® Language Specification, §15.12.3. Compile-Time Step 3: Is the Chosen Method Appropriate?

If the form is ExpressionName . [TypeArguments] Identifier or Primary . [TypeArguments] Identifier, then the compile-time declaration must not be a static method declared in an interface, or a compile-time error occurs.

In retrospect, the ability to invoke a static method through an instance is of little use, even less than the inheritance of static methods. I’m quite sure that a lot of developers consider it a design mistake that is only kept due to compatibility reasons.

For the newer feature of static methods in an interface, there was no compatibility constraint that required repeating this mistake, hence, the rules for static methods in interfaces were designed differently. This is also the solution with the smallest impact on compatibility with old code.

Related