Reputation: 2238
In Java 8 default
method implementation is introduced. My question is why the need to have default
keyword in the method name/signature. Why can't it be without the default
keyword just like a usual method implementation?
Upvotes: 0
Views: 2255
Reputation:
It is worth noting that since Java 8 interfaces also support static
methods. Leaving out the default
keyword opens the door to ambiguity: would a method declaration in an interface that has no modifier be implicitly static (like constants), or implicitly default? As it is, everything is clear.
Upvotes: 3
Reputation: 2016
Note: This is speculation, but educated speculation. What @Kayaman's answer says is also likely true.
Java aims to be as backward compatible as possible. If you didn't include the default keyword then potentially invalid code, perhaps written by mistake, in a previous java version now compiles on Java 8+. This can be viewed as breaking backwards compatibility.
Upvotes: 0
Reputation: 73528
It makes the intention clear. You can't accidentally create a default implementation for a method. Just like abstract
methods require the keyword, instead of just being methods without implementation.
A safety precaution for the careless programmers.
Upvotes: 8
Reputation: 1
In Java 8, “Default Method” or (Defender methods) feature, which allows the developer to add new methods to the interfaces without breaking their existing implementation. It provides the flexibility to allow interface to define implementation which will use as the default in a situation where a concrete class fails to provide an implementation for that method.
You can refer the below URL to understand more details. https://dzone.com/articles/interface-default-methods-java
Upvotes: -4