@Override, hiding and final¶
โ Java 17 ยท Rewriting What Your Parent Class Does ยท 2/3
Instance methods are overridden. Private methods, static methods and fields behave differently.
@Override checks your intent¶
class Content {
public void play() { }
}
class Movie extends Content {
@Override
public void play(int speed) { } // โ compiler error: nothing to override
}
Without the annotation, play(int) would silently become a new overloaded method. @Override tells the compiler this is meant to override something, and it refuses the code when no matching parent method exists. Put it on every override.
Private methods aren't inherited¶
class Content {
private String code() { return "C"; }
}
class Movie extends Content {
private int code() { return 7; } // โ
a new, unrelated method
}
The child doesn't inherit code(), so redeclaring it creates a separate method: none of the override checks apply, even the return type can differ.
Static methods are hidden, not overridden¶
When parent and child both declare a static method with the same signature, the child's version hides the parent's:
class Content {
static String brand() { return "ADC"; }
}
class Movie extends Content {
static String brand() { return "ADC Movies"; } // โ
hiding
}
Mixing static and instance never compiles:
class Content {
static void stop() { }
void pause() { }
}
class Movie extends Content {
void stop() { } // โ instance method vs static parent
static void pause() { } // โ static method vs instance parent
}
Access, exceptions and return types are checked when hiding too.
Fields: two copies¶
Fields are never overridden, only hidden. One object can hold two fields with the same name:
class Content {
String label = "content";
String describe() { return "a title"; }
}
class Movie extends Content {
String label = "movie";
String describe() { return "a movie"; }
}
Movie m = new Movie();
Content c = m;
m.label // movie
c.label // content โ the variable type decides
c.describe() // a movie โ the real object decides
| Member | Who decides which version? |
|---|---|
| fields and static methods (hidden) | the variable's type |
| instance methods (overridden) | the real object |
final locks a method¶
class Content {
public final String id() { return "42"; }
public final static void stop() { }
}
class Movie extends Content {
public String id() { return "7"; } // โ can't override a final method
public static void stop() { } // โ can't hide a final static method
}
A private final method isn't inherited, so a child may reuse its name freely.
The lab combines overriding, super, @Override and a final method in three subscription plans.