Reputation: 300
First of all, before you attempt to explain what an interface, and static and default methods are, I do not recommend it because that is not the question. I would also like to address this is NOT a duplicate of questions relating to the difference between or what are abstract/default methods. That is not the question.
So in an interface, you can have default methods and static methods. Both have an implementation. Both can be used in classes implementing the interface. The main difference I see is that static methods are not runnable through an object, while default methods are. However, they both have implementation, and are not "instance" in the sense that the two objects of the same type that implement the interface do not have instance variables located inside the interface... because interface variables are all static and final.
So because the only major difference is that one is runnable through the object while one is only runnable through the class... yet they do the same thing, why bother with static methods. In classes, you can invoke static methods through the object instance. In interfaces, you cannot. Default seems to just have an additional functionality so why ever choose to use a static instead of a default?
-Thanks
Upvotes: 1
Views: 744
Reputation: 691655
However, they both have implementation, and are not "instance" in the sense that the two objects of the same type that implement the interface do not have instance variables located inside the interface... because interface variables are all static and final.
No, you got this wrong. Default methods delegate to abstract methods. Abstract methods are implemented in concrete classes which implement the interface. Concrete classes very much have instance fields.
Example:
interface Counter {
void add(int i);
default void increment() {
this.add(1);
}
}
Implementation
class ConcreteCounter implements Counter {
private int value = 0;
@Override
public void add(int i) {
this.value += i;
}
}
A static method, just as static methods in classes, can't call instance methods, and are called on the interface class itself, and not on an instance of this interface. In the example above, you could for example have
interface Counter {
static Counter createDefault() {
return new ConcreteCounter();
}
void add(int i);
default void increment() {
this.add(1);
}
}
This static method can't possibly be implemented as a default method: it wouldn't make sense to have to create a Counter in order to be able to create a Counter.
To take a more concrete example, let's take the sort()
method of the List
interface. It sorts the elements of the list, and is a default method. It can't possibly be a static method: a static method isn't called on an instance of a List, so it can't possibly sort its elements.
So, basically, the difference between default methods and static methods in interfaces is the same difference there is between a static method and an instance method in a class.
Upvotes: 3