Translate

Search This Blog

Thursday 16 April 2020

What are the Interface enhancements in Java 8


Interface enhancements in Java 8

With Java 8, interfaces can now have default method and static method within the interface definition.

Default method, help to add new behaviour in the interface which if otherwise added would break all implementing classes. You can add default method through the use of the keyword default.

For Example,
If you notice the Iterator interface, it has added a new default method named forEachContaining(Consumer c) 

Similarly, Java 8 has modified many of its other interfaces to add new behaviour, but if you realise hasn't broken any functionality in the previous version (i.e. how it has maintained backward compatibility)

Static method, can also be added in the interfaces through the use of keyword static, except that they cant be overridden, exactly for the same reason as to why they weren't possible when associated with classes .

What happens to abstract classes?

Interfaces as earlier, still abstract out behaviour and can relate entities which are unrelated in hierarchy but common in behavioural interfaces.

For example: Sound interface with method makeSound still holds true when modelling Animal hierarchy and Instruments hierarchy.

Where as we would still use abstract classes when we want to abstract out common behaviour when there is strict hierarchy among classes.

What happens when two interfaces have default method with same signature?
Which also brings us to another point, what happens when two interfaces have common default method. Compiler complains saying "inherits unrelated defaults" and forces you to over ride the method.

No comments:

Post a Comment

Please use proper blogging etiquette while posting comments.

Note: only a member of this blog may post a comment.