As you, specialists, know in Java 8, interfaces can have static methods which have implementations inside themselves.
As I have read in a related tutorial, the classes which implement such interface can use its static methods. But, I have a problem which, here, I show it in a simpler example than what I have
public interface Interface1{
public static void printName(){
System.out.println("Interface1");
}
}
when I implement such interface
public class Class1 implements Interface1{
public void doSomeThing() {
printName();
}
}
I encounter compile error.
The method printName() is undefined for the type Class1
What's the problem?
Because static methods cannot be overridden in subclasses, and hence they cannot be abstract. And all methods in an interface are, de facto, abstract. You could always force each type to implement any static interface methods.
Static methods in an interface since java8 Since Java8 you can have static methods in an interface (with body). You need to call them using the name of the interface, just like static methods of a class.
You can't access static methods of interfaces through instances. You have to access them statically. This is a bit different from classes where accessing a static method through an instance is allowed, but often flagged as a code smell; static methods should be accessed statically.
You cannot override the static method of the interface; you can just access them using the name of the interface. If you try to override a static method of an interface by defining a similar method in the implementing interface, it will be considered as another (static) method of the class.
From the Java Language Specification,
A class C inherits from its direct superclass all concrete methods m (both static and instance) of the superclass for which all of the following are true:
- [...]
A class C inherits from its direct superclass and direct superinterfaces all abstract and default (§9.4) methods m for which all of the following are true:
- [...]
A class does not inherit static methods from its superinterfaces.
So that method is not inherited.
You can statically import the member
import static com.example.Interface1.printName;
...
printName();
or use it with the fully qualified type name
com.example.Interface1.printName();
or import the type to which printName
belongs and invoke it with its short name
import static com.example.Interface1;
...
Interface1.printName();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With