Interfaces Flashcards
What access modifiers do interfaces accept?
Only package and public
Why interfaces don’t have protected methods?
Because they are not extended by classes
Why interfaces don’t have package access methods?
Legacy reasons
Can interfaces have concrete methods?
Yes - default, static, private, private static
When overriding an abstract method, what are rules for return type?
Return type must be the same, or covariant
How do interfaces differ from abstract classes?
Interfaces have implicit modifiers, abstract classes do not
What is implicit regarding interfaces variables?
They are “public final”
What is implicit regarding interfaces?
They are abstract
What is implicit regarding interfaces methods?
Methods without bodies are “abstract”
Methods without “private” access modifier are “public” - if something else is defined -> compile error
What if different interfaces try to implement methods with same signatures?
Compile error because compiler doesn’t know which method to override or implement
eg.
interface A -> void int a()
interface B -> int eat()
What are methods inside interface?
They are abstract and public
What attributes do static methods inside interface have?
They are public, and cannot be abstract or final
How do we run static methods in interfaces?
Via interface name -> Interface.method()
Can default methods be overridden?
Yes
How can we access overridden (or hidden) default method from implemented interface?
InterfaceName.super.method()
Can static methods be overridden?
No
What if two different interfaces that are being implemented have same default method?
Then that method needs to be implemented in class
What if two different interfaces that are being implemented have default method with same signature, but different return type?
Compiler error, since it doesn’t know which method to implement, and both of them need to be implemented.
What if two different interfaces that are being implemented have method with same signature, but different return type?
Compiler error, since it doesn’t know which method to implement, and both of them need to be implemented.
What if two different interfaces that are being implemented don’t have same default methods?
Then none of default methods don’t need to be implemented in class
What are rules for default methods?
- Can be overridden
- Cannot be static, final, abstract
- Must have a method body
- Implicitly public, cannot be private or protected
What do we need to watch out when implementing multiple interfaces?
For double methods