32

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?

2
  • 1
    Related: stackoverflow.com/questions/129267/… Commented Apr 1, 2015 at 5:07
  • 1
    @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. Commented Apr 12, 2018 at 15:41

1 Answer 1

46

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.

Sign up to request clarification or add additional context in comments.

4 Comments

What about static methods from non-direct superclasses?
@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…
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 you just explained why it was a very good design decision, not to allow this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.