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

Why I can’t access the static methods of the 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 {
}
+4
source share
2 answers

Static interface methods are not inherited by subclasses

You cannot access static interface methods through instances. You must access them statically. This is slightly different from classes in which access to a static method through an instance is allowed, but is often flagged as code smell; static methods must be available statically.

, , - . & sect; 8.4.8 :

8.4.8. ,

& hellip;

.

, .

, , :

AWD.isRearWheelDrive()

, , , , , , , false:

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

. , , , , -. , , - :

  interface HasDriveWheels {
    boolean isRearWheelDrive();
  }

  interface AllWheelDrive extends HasDriveWheels {
    @Override
    default boolean isRearWheelDrive() {
      return false;
    }
  }
+7

Java®, §15.12.3. 3: ?

ExpressionName . [TypeArguments] Identifier Primary . [TypeArguments], static .

static , , static. , , .

static , , static -. .

+1

Source: https://habr.com/ru/post/1677903/


All Articles