Inheritance Gotchas
Explore key Java inheritance concepts, focusing on method overriding nuances, static method hiding, interface default method conflicts, and access control rules. Understand common pitfalls to avoid compile-time errors and write correct inheritance code.
We'll cover the following...
Consider the following Java class definitions:
public class Language {
static String lang = "base language";
static protected void printLanguage() {
System.out.println(lang);
}
protected Language sayHello() {
System.out.println("----");
return this;
}
}
public class Spanish extends Language {
static String lang = "Spanish";
static protected void printLanguage() {
System.out.println(lang);
}
protected Language sayHello() {
System.out.println("Ola!");
return this;
}
}
What will be printed by the following code?
(new Spanish()).sayHello();
“Ola!”
“----”
Consider the class setup below:
public interface Vehicle {
default void whatAmI() {
System.out.println("I am a vehicle");
}
}
public interface SevenSeater extends Vehicle {}
public interface SUV extends Vehicle {
default void whatAmI() {
System.out.println("I am a SUV");
}
}
public class TeslaModelX implements SUV, SevenSeater {
public void identifyMyself() {
whatAmI();
}
}
What will be the output of (new TeslaModelX()).identifyMyself()
will not compile
I am a SUV
I am a vehicle
Consider the class setup below:
public interface SuperPower {
void fly();
}
public class JetPack {
public void fly() {
System.out.println("fly away");
}
}
public class FlyingMan extends JetPack implements SuperPower {
void identify() {
System.out.println("I am a flying man.");
}
}
The class FlyingMan implements the interface SuperPower but doesn’t provide an implementation for it directly. Will this code snippet compile since the class JetPack has a fly method?
No
Yes, because the inherited public fly() method in JetPack satisfies the interface requirement.
Consider the two classes below:
class Parent {
public void dummyMethod(){
}
}
class Child extends Parent {
protected void dummyMethod(){
}
}
What is the issue with how the method access modifiers are used in this code?
Both the class declarations are missing the access modifiers
The overridden method dummyMethod in the Child class uses a more restrictive access modifier than in the Parent class, which is not allowed in Java.
dummyMethod has no method body
Takeaways
- Instance methods in base classes can be overridden by derived classes.
- If a subclass defines a static method