Default interface methods Flashcards

1
Q

Define a default method in the context of interfaces !

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the difference between the default access modifier and the default method ?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Give the default interface method rules !

A

The following are the default interface method rules you need to be familiar with:

  1. A default method may only be declared within an interface and not within a class or abstract class.
  2. A default method must be marked with the default keyword. If a method is marked as default, it must provide a method body.
  3. 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.
  4. Like all methods in an interface, a default method is assumed to be public and will not compile if marked as private or protected.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What can happen when an interface extends another interface that declares a default method ?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What happens If a class implements two interfaces that have default methods with the same name and signature ?

A

It will result in a compilation error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Give an exception to that rule with an example !

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly