Default interface methods Flashcards
Define a default method in the context of interfaces !
A default method in the context of interfaces is the only method that must have a body within an interface, it is declared using the keyword ‘default’, and if any class or interface extends or implements that interface, it can choose to override or not that default method.
What is the difference between the default access modifier and the default method ?
The difference between the default access modifier and the default method is that the default access modifier is the lack of any access modifier in a method declaration but the default method is a method that can only be declared inside an interface using the keyword ‘default’ in its method declaration
Give the default interface method rules !
The following are the default interface method rules you need to be familiar with:
- A default method may only be declared within an interface and not within a class or abstract class.
- A default method must be marked with the default keyword. If a method is marked as default, it must provide a method body.
- A default method can not to be static, final, or abstract, as it may be used or overridden by a class that implements the interface.
- Like all methods in an interface, a default method is assumed to be public and will not compile if marked as private or protected.
What can happen when an interface extends another interface that declares a default method ?
When an interface extends another interface that declares a default method, the last interface can either choose to override the default method, redeclare the default method as abstract or inherits the default method without providing any new implementation for it
What happens If a class implements two interfaces that have default methods with the same name and signature ?
It will result in a compilation error
Give an exception to that rule with an example !
If the class implementing the 2 interfaces overrides one of the methods, the code will compile since the ambiguity on which method to use has been removed