Java Inheritance and Class Modifiers: extends, Object, this and super (OCP 21)
Inheritance basics for the OCP Java 21 exam: extends and single inheritance, java.lang.Object as the root of every class, which members a subclass inherits, final and other class modifiers, top-level class access, and how this and super resolve fields and methods.
kvi5hnuCode Sprout team member8 min readOn this page
Chapter 6 is about designing classes that build on each other. This chapter is among the most heavily tested on the exam, and every later chapter relies on it. It starts here with inheritance: a subclass (child) automatically includes the accessible members of its superclass (parent), so you can reuse and extend behavior instead of copying it. Interfaces use the more general words subtype and supertype, which you'll see in Chapter 7.
Declaring a subclass
public class Vehicle {
protected String plate;
public void drive(int km) { ... }
}
public class Truck extends Vehicle { // Truck IS-A Vehicle
public void load(int kg) { ... }
}
The extends keyword names the parent. The parent doesn't need to declare anything special, as long as it isn't final, its constructors are accessible (article 32), and it's a class rather than an interface (class C extends SomeInterface fails with "no interface expected here").
Inheritance is transitive. If ElectricTruck extends Truck and Truck extends Vehicle, then ElectricTruck is also a subclass (a descendant) of Vehicle. Its direct superclass is only Truck.
What a subclass inherits

| Parent member | Inherited by the subclass? |
|---|---|
public | yes |
protected | yes, in any package |
| package access | only if the subclass is in the same package |
private | no |
Private members are never inherited. They still exist inside every object of the subclass, because the parent's code needs them, but the subclass can't name them. It reaches them only through accessible methods that the parent provides:
public class Account {
private int pin;
protected String owner;
public int getPin() { return pin; }
public void setPin(int pin) { this.pin = pin; }
}
public class Savings extends Account {
void setup(int pin, String o) {
setPin(pin); // fine: inherited public method
owner = o; // fine: inherited protected field
this.pin = pin; // DOES NOT COMPILE: pin has private access in Account
}
}
A class that isn't related, such as Printer, can't use the inherited fields at all. Inheritance gives access only to subclasses.
Constructors aren't inherited, and neither are static and instance initializers. Each class declares its own constructors (article 32).
Single inheritance
A Java class has exactly one direct superclass. Multiple inheritance of classes is not supported:
class Tablet extends Phone, Laptop { } // DOES NOT COMPILE
This avoids the classic "diamond" problem: if two parents both declared a field or method with the same name, which one would the child get? A class can have any number of levels of ancestors and any number of children, but only one parent. Java gets some of the benefits of multiple inheritance safely through interfaces: a class can implement many interfaces (Chapter 7).
java.lang.Object: the root of every class
Every class you write inherits, directly or indirectly, from java.lang.Object. If you don't write extends, the compiler adds extends java.lang.Object for you:
public class Garage { } // what you write
public class Garage extends java.lang.Object { } // what the compiler sees
If you do extend another class, you don't extend Object directly, but you still inherit from it through the chain. Object is the only class with no superclass, so following getSuperclass() from any class always ends at Object.
That's why every object has methods such as toString(), equals(Object), hashCode() and getClass(). Their default versions aren't very useful, which is why classes usually override them (article 34).
Primitives aren't objects and don't extend Object. Arrays do: an int[] is an Object. Through autoboxing, a primitive can be passed where an Object is expected, as a wrapper.
Class modifiers
| Modifier | Meaning | Covered in |
|---|---|---|
final | the class can't be extended | here |
abstract | the class can't be instantiated and may have abstract methods | article 35 |
sealed | only the listed classes may extend it | Chapter 7 |
non-sealed | a subclass of a sealed class that is open again to any subclass | Chapter 7 |
static | only for nested classes | Chapter 7 |
public class Tool { }
public final class Hammer extends Tool { }
public class MiniHammer extends Hammer { } // DOES NOT COMPILE: cannot inherit from final Hammer
On the exam, when you see a final class, check whether anything tries to extend it. String, Integer and the other wrapper classes, Math and LocalDate are all final in the JDK.
abstract final together is an "illegal combination of modifiers", because an abstract class exists only to be extended. static isn't allowed on a top-level class.
Access for top-level classes
A top-level class (one that isn't nested inside another) can only be public or package-access:
// Notes.java
class Pen { }
class Notes { } // several package-access classes in one file are fine
class Ink { }
protected class Clip { } // DOES NOT COMPILE
private class Pad { } // DOES NOT COMPILE
A file can contain at most one public top-level class, whose name must match the file name. It doesn't need to contain any public class at all. Nested classes can use all four access levels (Chapter 7).
The this reference
this refers to the current object. You need it when a local variable or parameter has the same name as a field, because Java resolves a simple name to the narrowest scope first:
public class Banner {
private String color;
public void setColor(String color) {
color = color; // assigns the parameter to itself: the field stays null
}
public void fixColor(String color) {
this.color = color; // assigns the field
}
}
The first method compiles, which makes it a favorite trap. It does nothing useful.
Watch for assignments written backwards, too:
public class Frame {
private int width, height;
private String color;
public void setSize(int width, int newHeight) {
width = this.width; // copies the field (0) INTO the parameter: backwards
height = newHeight; // fine: different names, no this needed
this.color = "black"; // fine: this is optional here
}
}
// new Frame().setSize(1, 2) leaves width 0, height 2, color "black"
You can use this in any instance method, constructor or instance initializer. It doesn't exist in static methods or static initializers, because there's no current object.
The super reference
super refers to the inherited members of the current object, the ones from the parent class. It skips any member declared in the current class. You need it when the child declares something with the same name as the parent:
class Device {
protected int ports = 2;
String label = "dev";
}
public class Laptop extends Device {
protected int ports = 4; // HIDES Device.ports: the object now has two ports fields
short gen = 3;
void print() {
System.out.println(this.label); // dev (inherited, reachable through this)
System.out.println(super.label); // dev
System.out.println(this.gen); // 3
System.out.println(super.gen); // DOES NOT COMPILE: gen isn't inherited
System.out.println(ports); // 4: the narrowest scope wins
System.out.println(super.ports); // 2
}
}
this.xfindsxin the current class or any ancestor.super.xfindsxonly in the ancestors.- A plain
xchecks local variables first, thenthis.
Declaring a field with the same name as an inherited one is called hiding (article 34). Both fields exist, and which one you get depends on the reference used. Hiding fields is legal, but it's almost always a design mistake.
super.method() calls the parent's version of a method, which is common when an overriding method wants to extend the parent's behavior instead of replacing it:
@Override
public String describe() {
return "Truck " + super.describe();
}
super starts its search at the parent class, and finds the member there or in a further ancestor if the parent doesn't declare it. There's no way to skip a level: super.super.x is not valid syntax. Like this, super can't be used in a static context.
What's current
- Java 25 finalized flexible constructor bodies (JEP 513): statements may appear before
super(...)orthis(...)if they don't use the object being built. On Java 21 the call must come first (article 32). - Everything else here, including single inheritance,
Objectas the root and the rules forthisandsuper, is unchanged through Java 25.
Exam traps from this article
A complete example
The program builds a three-level hierarchy that ends in a final class. It uses inherited private state through a getter, assigns a field through this, calls the parent's method through super, and shows how a hidden field gives different values depending on the reference. Finally, it walks the superclass chain up to Object.
public class Solution {
static class Vehicle { // implicitly: extends Object
private int mileage; // not visible to subclasses
protected String plate; // inherited by subclasses
protected int wheels = 4;
public int getMileage() { return mileage; }
public void drive(int km) { mileage += km; }
public String describe() { return plate + " with " + wheels + " wheels"; }
}
static class Truck extends Vehicle {
protected int wheels = 6; // HIDES Vehicle.wheels: two fields now exist
void register(String plate) {
this.plate = plate; // parameter shadows the field: this. is required
}
String wheelReport() {
return "this.wheels=" + this.wheels + ", super.wheels=" + super.wheels
+ ", ((Vehicle) this).wheels=" + ((Vehicle) this).wheels;
}
@Override
public String describe() {
return "Truck " + super.describe(); // reuse the parent's version
}
}
// final: no class may extend ElectricTruck.
static final class ElectricTruck extends Truck {
private final int batteryKwh;
ElectricTruck(String plate, int batteryKwh) {
register(plate); // inherited method
this.batteryKwh = batteryKwh;
}
@Override
public String describe() {
return super.describe() + ", " + batteryKwh + " kWh";
}
}
static String ancestry(Class<?> type) {
var sb = new StringBuilder(type.getSimpleName());
for (Class<?> c = type.getSuperclass(); c != null; c = c.getSuperclass()) {
sb.append(" -> ").append(c.getSimpleName());
}
return sb.toString();
}
public static void main(String[] args) {
var truck = new ElectricTruck("EV-204", 540);
truck.drive(120);
truck.drive(35);
System.out.println(truck.describe());
System.out.println("mileage via inherited getter: " + truck.getMileage());
System.out.println(truck.wheelReport());
// Which field you get depends on the reference type, because fields are not overridden.
Vehicle asVehicle = truck;
Truck asTruck = truck;
System.out.println("asVehicle.wheels=" + asVehicle.wheels + ", asTruck.wheels=" + asTruck.wheels);
System.out.println(ancestry(ElectricTruck.class));
System.out.println("is an Object? " + (truck instanceof Object)
+ ", final class? " + java.lang.reflect.Modifier.isFinal(ElectricTruck.class.getModifiers()));
}
}
Output:
Truck EV-204 with 4 wheels, 540 kWh
mileage via inherited getter: 155
this.wheels=6, super.wheels=4, ((Vehicle) this).wheels=4
asVehicle.wheels=4, asTruck.wheels=6
ElectricTruck -> Truck -> Vehicle -> Object
is an Object? true, final class? true
Points to notice:
describe()inVehicleprints4 wheels, even for the truck. Code inVehicleseesVehicle.wheels, because fields aren't overridden. That's why hiding fields is a design smell.this.wheels,super.wheelsand((Vehicle) this).wheelsshow that both fields exist in the same object.asVehicle.wheelsandasTruck.wheelsdiffer for the same object, because field access uses the reference type.- Each
describe()override callssuper.describe(), so the output builds up level by level.
Common questions
Does a subclass inherit static members?
Accessible static members can be used from a subclass (Truck.someStaticMethod() finds the one declared in Vehicle). They belong to the class where they're declared and are never overridden, only hidden (article 34).
Is Object imported automatically?
Yes. Everything in java.lang is.
Should I use inheritance for code reuse? Use it only when there's a true IS-A relationship. "Favor composition over inheritance" (holding a reference to a helper object) is common advice, because deep hierarchies are rigid.
What does final on a class buy you?
It guarantees that the behavior can't be changed by a subclass. That's important for security and immutability (String), and it lets the JVM optimize. Records (Chapter 7) are implicitly final.
Summary
class B extends AmakesBinheritA's public and protected members, and its package members when both classes are in the same package. Private members and constructors aren't inherited.- Java classes have exactly one direct parent. Inheritance chains always end at
java.lang.Object, which is added implicitly when there's noextends. finalclasses can't be extended. Top-level classes can only bepublicor package-access.thisrefers to the current object and solves name clashes with parameters.superreaches only inherited members, searching from the parent upward.- A plain name resolves to the narrowest scope first: local variable, then the class's own field, then inherited fields.
Practice quiz
Test yourself with the inheritance and class modifiers quiz: 10 exam-style questions with explanations.
Previous: Java Method Overloading and Overload Resolution (OCP 21)
Next: Java Constructors: Default Constructor, this() and super() (OCP 21)
Related reading
- Java while, do/while, for and for-each Loops (OCP 21)
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
- Java Packages and Imports: Wildcards, Conflicts, Compiling and the Class Path (OCP 21)
- Java Building Blocks: JDK, JVM, Class Structure and the main Method (OCP 21)
- Writing a Class Loader and Bytecode Verification in Java

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.