Java Method Overriding and Hiding: Rules, final Methods and Static Hiding (OCP 21)
Java method overriding for the OCP 21 exam: the four compiler rules (signature, access, checked exceptions, covariant returns), @Override, redeclaring private methods, hiding static methods and fields, final methods, and how each is chosen at run time or compile time.
kvi5hnuCode Sprout team member8 min readOn this page
When a subclass declares a member with the same name as one it inherits, three different things can happen. It can override the member, hide it, or simply declare an unrelated new one. Which of these happens decides both whether the code compiles and what it prints, so the exam tests the difference constantly.
Overriding an instance method
A subclass overrides an inherited instance method when it declares an instance method with the same signature, meaning the same name and the same parameter types. The new version replaces the old one for every object of the subclass, whatever the type of the reference used to call it:
class Kettle {
double capacity() { return 1.5; }
}
class TravelKettle extends Kettle {
@Override
double capacity() { return super.capacity() - 1.0; } // calls the parent version
}
Kettle k = new TravelKettle();
System.out.println(k.capacity()); // 0.5: the object's version runs
super.capacity() reaches the parent's version. Without super, a call to capacity() inside TravelKettle.capacity() would call itself again, recurse forever and throw StackOverflowError at run time. It still compiles.
You can only use super to reach your direct parent. super.super.method() doesn't compile.
The four compiler rules
An override compiles only if:
| # | Rule | javac message when broken |
|---|---|---|
| 1 | Same signature (name and parameter types). | (not an override at all, see below) |
| 2 | Access is the same or wider than the parent method's. | "attempting to assign weaker access privileges; was public" |
| 3 | No new or broader checked exceptions. Fewer, narrower or unchecked exceptions are fine. | "overridden method does not throw FileNotFoundException" |
| 4 | The return type is covariant: the same type, or a subtype for reference types. | "return type long is not compatible with int" |
Every one of these rules comes from the same idea. Code written against the parent type must stay correct when a subclass object turns up at run time. A caller holding a Kettle reference expects to be able to call capacity(), to handle only the exceptions Kettle declares, and to get back something it can store as a double.
Rule 1. If the parameter lists differ, it's an overload, not an override. Both methods exist side by side.
Rule 2. Access can only get wider. The order is private < package < protected < public.
class Camera { public int zoom() { return 3; } }
class PhoneCamera extends Camera {
int zoom() { return 2; } // DOES NOT COMPILE: package access is narrower than public
}
Rule 3 applies only to checked exceptions:
class Uploader {
protected void send() throws IOException { }
protected void ping() { }
protected void close() throws FileNotFoundException { }
}
class S3Uploader extends Uploader {
public void send() throws FileNotFoundException { } // OK: narrower checked exception
public void ping() throws IllegalStateException { } // OK: unchecked exceptions are always allowed
public void close() throws IOException { } // DOES NOT COMPILE: broader than FileNotFoundException
}
Declaring no exceptions at all is also a legal override of send() throws IOException. Adding a checked exception to a method that declared none, such as ping() throws IOException, fails. Chapter 11 covers the exception hierarchy. For now, remember that FileNotFoundException is a checked subclass of IOException.
Rule 4. To check covariance, ask: "can I assign the child's return value to a variable of the parent's return type without a cast?"
class Shelf {
protected CharSequence label() { return "shelf"; }
protected String code() { return "S-1"; }
protected Object item() { return 1; }
protected int count() { return 1; }
}
class WallShelf extends Shelf {
public String label() { return "wall"; } // OK: String is a CharSequence
public CharSequence code() { return "W"; } // DOES NOT COMPILE: CharSequence isn't a String
public Integer item() { return 2; } // OK: Integer is an Object
public long count() { return 2; } // DOES NOT COMPILE: primitive return types must match exactly
}
For primitives the rule is strict. Overriding int count() with long count() fails, even though an int widens to a long. Overriding Integer m() with int m() also fails, because autoboxing doesn't apply to return types in overrides. A void method can only be overridden by a void method. Covariant returns also work with generics, so ArrayList<String> list() can override List<String> list(). Chapter 9 revisits generic overriding.
The @Override annotation
@Override asks the compiler to confirm that the method really overrides something. Use it on every override. It turns a silent overload into a compile error:
class Pump { void start() { } }
class FuelPump extends Pump {
@Override void start(int rpm) { } // DOES NOT COMPILE: method does not override or implement a method from a supertype
}
Without the annotation, start(int) would compile as a new overload, and start() would still run the parent's code. @Override can't be placed on a static method ("static methods cannot be annotated with @Override"). On the exam, the annotation on an invalid method is itself a reason for a compile error.
private methods aren't inherited, so they can be redeclared
A private method isn't inherited, so a subclass method with the same name is a brand-new, unrelated method. None of the four rules apply:
class Sensor {
private String reading() { return "n/a"; }
}
class TempSensor extends Sensor {
private int reading() { return 21; } // compiles: a separate method, return type can differ
}
If Sensor.reading() were public instead, the same child method would be an invalid override, with weaker access and an incompatible return type. Adding @Override to a method that "overrides" a private one also fails, because there's nothing to override.
The same logic applies across packages. A package-access method isn't inherited by a subclass in a different package, so the subclass's same-named method is unrelated to it. Code in the parent's package that calls the method still gets the parent's version.
Hiding static methods
Static methods belong to the class, not to objects, so they can't be overridden. A child static method with the same signature hides the parent's. All four overriding rules still apply, plus a fifth:
- If one method is
static, the other must be too. Mixing static and instance methods doesn't compile.
class Printer {
public static void warmUp() { }
public void feed() { }
public static void reset() { }
}
class LaserPrinter extends Printer {
public void warmUp() { } // DOES NOT COMPILE: overridden method is static
public static void feed() { } // DOES NOT COMPILE: overriding method is static
protected static void reset() { } // DOES NOT COMPILE: weaker access (rule 2 still applies)
}
The practical difference is which version runs. A hidden static method is chosen at compile time, from the type named in the call (or the declared type of the reference). An overridden instance method is chosen at run time, from the object:

Inside the parent class's own methods, a call to a hidden static method always runs the parent's version. Only overridden instance methods are polymorphic.
Hiding fields
Fields are never overridden. A child field with the same name as an inherited field hides it, and the object then holds two separate fields:
class Lamp { protected String color = "white"; }
public class DeskLamp extends Lamp {
protected String color = "green";
public static void main(String[] args) {
DeskLamp d = new DeskLamp();
Lamp l = d;
System.out.println(d.color); // green: chosen by the reference type DeskLamp
System.out.println(l.color); // white: chosen by the reference type Lamp
}
}
There are no type or modifier rules for hiding a field. The hiding field can have a different type, or be static where the parent's is an instance field. Inside the child, super.color reaches the parent's copy.
final methods
A final method can't be overridden, and a final static method can't be hidden:
class Badge {
public final boolean isValid() { return true; }
public static final void audit() { }
}
class TempBadge extends Badge {
public boolean isValid() { return false; } // DOES NOT COMPILE: overridden method is final
public static void audit() { } // DOES NOT COMPILE: overridden method is static,final
}
Whether the child method is itself marked final doesn't matter. The parent's final is what blocks it. The rule only covers inherited methods, so if isValid() were private final in Badge, the child's isValid() would be a legal new method.
Use final on methods whose behavior subclasses must not change, such as methods called from constructors (article 33) or security checks. To stop all overriding at once, mark the whole class final (article 31) or sealed (chapter 7).
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Put
@Overrideon every overriding method. The compiler then rejects a method that only looks like an override, which is exactly the kind of mistake exam questions hide.
Exam traps from this article
A complete example
This program uses one Invoice object through an Invoice reference and through a Document reference to show an overridden method, a hidden field, a hidden static method, a narrower throws clause and a final method side by side.
import java.io.FileNotFoundException;
import java.io.IOException;
public class Solution {
static class Document {
String label = "document"; // will be hidden
static String kind() { return "Document.kind"; } // will be hidden
CharSequence title() { return "Untitled"; } // will be overridden
protected void save() throws IOException { // will be overridden
System.out.println(" Document.save");
}
final String id() { return "DOC-1"; } // cannot be overridden
String describe() {
// title() is chosen at run time; label and kind() are fixed here
return title() + " | " + label + " | " + kind();
}
}
static class Invoice extends Document {
String label = "invoice"; // hides Document.label
static String kind() { return "Invoice.kind"; } // hides Document.kind()
@Override
public String title() { // covariant return, wider access
return "Invoice #42 (was: " + super.title() + ")";
}
@Override
public void save() throws FileNotFoundException { // narrower checked exception
System.out.println(" Invoice.save, then:");
try {
super.save();
} catch (IOException e) {
System.out.println(" never happens here");
}
}
}
public static void main(String[] args) throws IOException {
Invoice inv = new Invoice();
Document doc = inv; // same object, parent-type reference
System.out.println("Overridden method, either reference:");
System.out.println(" inv.title() = " + inv.title());
System.out.println(" doc.title() = " + doc.title());
System.out.println("Hidden field, picked by reference type:");
System.out.println(" inv.label = " + inv.label);
System.out.println(" doc.label = " + doc.label);
System.out.println("Hidden static method, picked by the type you name:");
System.out.println(" Invoice.kind() = " + Invoice.kind());
System.out.println(" Document.kind() = " + Document.kind());
System.out.println("Inside an inherited method:");
System.out.println(" " + doc.describe());
System.out.println("Calling save() through the Document reference:");
doc.save();
System.out.println("final method: " + inv.id());
}
}
Output:
Overridden method, either reference:
inv.title() = Invoice #42 (was: Untitled)
doc.title() = Invoice #42 (was: Untitled)
Hidden field, picked by reference type:
inv.label = invoice
doc.label = document
Hidden static method, picked by the type you name:
Invoice.kind() = Invoice.kind
Document.kind() = Document.kind
Inside an inherited method:
Invoice #42 (was: Untitled) | document | Document.kind
Calling save() through the Document reference:
Invoice.save, then:
Document.save
final method: DOC-1
Points to notice:
title()returnsStringinInvoicebutCharSequenceinDocument, which is a covariant return. Its access also widens topublic. It runs theInvoiceversion through both references.labelprints differently depending on the reference type, because the object has twolabelfields.describe()is written inDocument. Inside it,title()is polymorphic, butlabelandkind()are fixed toDocument's members at compile time.Invoice.save()declaresFileNotFoundException, which is narrower thanIOException.mainstill has to handleIOException, because it callssave()through aDocumentreference.
Common questions
What's the difference between overriding and overloading again? Overriding is the same signature in a subclass, chosen at run time by the object. Overloading is the same name with different parameters, in the same class or a subclass, chosen at compile time by the arguments (article 30).
Can a constructor be overridden? No. Constructors aren't inherited, so there's nothing to override (article 32).
Can an override add final, synchronized or strictfp?
Yes. Those modifiers aren't part of the overriding rules. strictfp has done nothing since Java 17, and javac warns that it's redundant.
Do these rules apply to interface methods?
Yes. Implementing an interface method is overriding, with the same four rules. Because interface methods are implicitly public, the implementation must be public too. Chapter 7 covers this.
Summary
- Overriding means the same signature, the same or wider access, no new or broader checked exceptions, and a covariant return type. Use
@Overrideto have the compiler verify it. - An overridden instance method is chosen at run time from the object.
super.m()reaches the parent's version. - Static methods with the same signature hide each other. Both must be static, the four rules still apply, and the version is chosen at compile time.
- Fields are hidden, never overridden: the reference type decides which copy you see.
private(and other non-inherited) methods can be redeclared freely.finalmethods can't be overridden or hidden.
Practice quiz
Test yourself with the overriding and hiding quiz: 10 exam-style questions with explanations.
Previous: Java Initialization Order and final Fields (OCP 21)
Related reading
- Java Initialization Order and final Fields (OCP 21)
- Java Constructors: Default Constructor, this() and super() (OCP 21)
- Java Inheritance and Class Modifiers: extends, Object, this and super (OCP 21)
- Java Method Overloading and Overload Resolution (OCP 21)
- Java Pass-by-Value, Returning Objects and Autoboxing (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.