Inheritance Gotchas
Explore common pitfalls in Java inheritance, including how instance methods are overridden, the behavior of static methods, and conflicts with interface default methods. Understand access specifier rules and compiler errors related to overriding and hiding methods. This lesson helps clarify nuanced behaviors to improve your Java coding and debugging skills in object-oriented design.
We'll cover the following...
Consider the setup below:
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 would be the outcome of the below code snippet?
(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
Consider the two classes below:
class Parent {
public void dummyMethod(){
}
}
class Child extends Parent {
protected void dummyMethod(){
}
}
What is wrong with the above code?
Both the class declarations are missing the access modifiers
The overridden method dummyMethod in the Child class is specified a more restrictive access modifier than in the Parent class.
dummyMethod has no method body
Takeaways
- Instance methods in base classes can be overridden by derived classes.
- If a subclass defines a static method