Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Interface methods cannot be "static" & "final"?

In Java Interface, we can have only final variables possible. We can also create static variables in Interface. But, at the same time we are not able to create static/final methods as Interface are only meant for Static Methods.

What is exactly the reason for not allowing static/final methods in Interface ?

like image 695
Sarang Avatar asked May 20 '12 12:05

Sarang


People also ask

Why static method is not allowed in interface?

This is because it's not allowed in java, since Object is the base class for all the classes and we can't have one class level static method and another instance method with same signature.

CAN interface have a static method?

Similar to Default Method in Interface, the static method in an interface can be defined in the interface, but cannot be overridden in Implementation Classes. To use a static method, Interface name should be instantiated with it, as it is a part of the Interface only.


2 Answers

You got it wrong.

  1. All variables are implicitly public static and final in interfaces.

  2. Prior to Java 8, you can't create static methods in interfaces. All methods are instance methods.

  3. Since the only goal of an interface is to have classes implementing them, and since methods in interfaces can't have any implementation, making them final would make no sense: they would have no implementation, and could not be overridden.

like image 138
JB Nizet Avatar answered Sep 28 '22 01:09

JB Nizet


final means that it cannot be overriden.

static means that it can only be called using the class name. Since an interface will have multiple implementations, how will you know which implementation to choose since the interface cannot implement the method itself?

like image 23
Varun Achar Avatar answered Sep 28 '22 02:09

Varun Achar