Inheriting an interface Flashcards
Give inheritance rules you should keep in mind when extending an interface !
There are 2 inheritance rules you should keep in mind when extending an interface :
- An interface that extends another interface as well as an abstract class that implements an interface inherit all of its abstract methods as its own
- The first concrete class to implement an interface or to extend an abstract class must provide an implementation for all the abstract methods
Give an example of a concrete class extending an abstract class that implements 2 interfaces !
public interface HasTail {
public int getTailLength();
}
public interface HasWhiskers {
public int getNumberOfWhiskers();
}
public abstract class HarborSeal implements HasTail, HasWhiskers {
}
public class LeopardSeal implements HasTail, HasWhiskers { // DOES NOT COMPILE
}
HarborSeal is an abstract class and compiles without issue.
Any class that extends HarborSeal will be required to implement all of the methods in the HasTail and HasWhiskers interface.
Alternatively, LeopardSeal is not an abstract class, so it must implement all the interface methods within its definition
Give a common pitfall related to the keywords ‘extends’ and ‘implements’ when it comes to interfaces and classes !
A common pitfall is to use the keyword ‘implements’ instead of ‘extends’ when an interface extends another interface.
The second pitfall is to use the keyword ‘extends’ instead of ‘implements’ when an abstract or concrete class implements an interface
What will happen if you define a class that inherits from two interfaces that contain the same abstract method ?
If you define a concrete class that implements 2 interfaces that contain the same abstract method, the concrete class has to give an implementation to that abstract method and by doing that, it will override both of the abstract methods at the same time
What happens if the two methods have different signatures?
If a concrete class implements 2 interfaces , each of them has an abstract method similar to the other in terms of the name or the parameter list, the concrete class will have to implement each one of those methods
What happens if the method name and input parameters are the same but the return types are different between the two methods ?
If a concrete class implements 2 interfaces that contain abstract methods with the same signature but different return types, it will result in a compilation error because it is not allowed in java to define methods with the same name and parameter lists but different return types.
What happens if you define an interface or abstract class that inherits from 2 interfaces that define abstract methods with the same signature but different return types ?
If you define an interface or an abstract class that extends or implements 2 interfaces with abstract methods that have the same signature but different return types, this will result in a compilation error