31

I'm playing around Java 8's new features recently and observed an interesting behaviour:

This is okay:

Class A { static void staticMethodInA() {println();} }
Class B extends A {}

B.staticMethodInA();

This would induce an error of: static method may be invoked on containing interface class only.

interface A { static void staticMethodInA() {println();} }
Class B implements A {}

B.staticMethodInA(); // from here IntelliJ complaints..

Can someone tell me why the designer of Java 8 may choose to treat the above 2 cases differently?

Naman
  • 27,789
  • 26
  • 218
  • 353
SexyNerd
  • 1,084
  • 2
  • 12
  • 21
  • 1
    Related: http://stackoverflow.com/questions/129267/why-no-static-methods-in-interfaces-but-static-fields-and-inner-classes-ok – skaffman Apr 01 '15 at 05:07
  • @skaffman The related question is not about Java 8. It asks, "why aren't static methods available in interfaces prior to Java 8?" This question asks, "In Java 8, which allows static methods in interfaces, why can't we call static methods from classes that implement the interface?" Not a big deal, and while the related post may answer the question, this question is not technically a duplicate of the related post. – John Apr 12 '18 at 15:41

1 Answers1

44

Addition of static methods in interface in Java 8 came with 1 restriction - those methods cannot be inherited by the class implementing it. And that makes sense, as a class can implement multiple interface. And if 2 interfaces have same static method, they both would be inherited, and compiler wouldn't know which one to invoke.

However, with extending class, that's no issue. static class methods are inherited by subclass.

See JLS §8.4.8:

A class C inherits from its direct superclass all concrete methods m (both static and instance) of the superclass

...

A class C inherits from its direct superclass and direct superinterfaces all abstract and default (§9.4) methods m

...

A class does not inherit static methods from its superinterfaces.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • What about static methods from non-direct superclasses? – Abhijit Sarkar Jul 21 '17 at 20:19
  • 1
    @Abhijit Sarkar: a class inherits from its direct superclass *all* concrete methods, including those that the direct superclass inherited from the superclass of the superclass and so forth… – Holger Oct 13 '17 at 12:21
  • It's a shame they restricted it. Interfaces with static methods could have been used for creating modules/namespaces and then composed into one uber-library such as Predef in scala. Instead I have to either use 10 static imports or mix them in using inheritance which I don't like... – piotrga Aug 10 '20 at 08:43
  • 2
    @piotrga you just explained why it was a very good design decision, not to allow this. – Holger Nov 18 '20 at 13:22