Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java 8, why cannot call the interface static method that the current class is implementing [duplicate]

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?

like image 584
SexyNerd Avatar asked Apr 01 '15 04:04

SexyNerd


People also ask

Why static method is not allowed in interface?

Java interface static method helps us in providing security by not allowing implementation classes to override them. We can't define interface static method for Object class methods, we will get compiler error as “This static method cannot hide the instance method from Object”.

Does Java 8 allow static methods in interfaces?

Java 8 brought a few brand new features to the table, including lambda expressions, functional interfaces, method references, streams, Optional, and static and default methods in interfaces.

Can a static method of an interface be called by an implementing class that does not override the static method?

No. Static method can invoke only on interface class not on class. Interface and implementing class , both can have static method with the same name without overriding each other.

Why can't static methods call the instance methods present in the same class?

Within a static method, you do not have an instance of the class. So it will be impossible to call an instance method on an instance when no instance exists.


1 Answers

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.

like image 191
Rohit Jain Avatar answered Sep 19 '22 16:09

Rohit Jain