| Start | ||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Basic usage of default methods The following statements Will produce this output:
|
||||||||||||||||||
| Accessing overridden default methods from implementing class In classes, |
||||||||||||||||||
| Why use Default Methods? The simple answer is that it allows you to evolve an existing interface without breaking existing implementations. For example, you have We did a great job, our interface is very popular, there are many implementation on that around the world and you don't have control over their source code. After 20 years, you've decided to add new functionality to the interface, but it looks like our interface is frozen because it will break existing implementations. Luckily Java 8 introduces brand new feature called Default method. (opens new window) We can now add new method to the Now all existing implementations of our interface can still work. But most importantly they can implement the newly added method in their own time. One of the biggest reasons for this change, and one of its biggest uses, is in the Java Collections framework. Oracle could not add a |
||||||||||||||||||
| Accessing other interface methods within default method You can as well access other interface methods from within your default method. The following statement will print 3: Default methods could be used along with interface static methods as well: The following statement will also print 3: |
||||||||||||||||||
| Default method multiple inheritance collision Consider next example: Here are two interfaces declaring If you will try to First, you can declare method And when you will Or second, you can provide a completely new And when you will |
||||||||||||||||||
| Class, Abstract class and Interface method precedence Implementations in classes, including abstract declarations, take precedence over all interface defaults.
The following statement Will produce
The following statement Will produce Syntax
RemarksDefault methodsStatic methodsBelow is a table summarizing the interaction between sub-class and super-class.
Below is a table summarizing the interaction between interface and implementing-class.
References : |
Read Article
https://develop.horje.com/learn/1434/reference