Java final Classes and Methods, Casting, instanceof Patterns and protected Access
Control and navigate Java class hierarchies: final classes and methods (and why constructors should never call overridable methods), casting object references safely, ClassCastException, pattern matching for instanceof, record patterns, and how protected access really works.
kvi5hnuCode Sprout team member13 min readOn this page
Inheritance and dynamic binding are powerful, but sometimes you need to limit them, or step back down a hierarchy from a general type to a specific one. This article covers four tools for that:
finalclasses and methods, which stop inheritance and overriding,- casts, which convert a superclass reference to a subclass type,
- pattern matching for
instanceof, the modern, safe way to test and cast, and protectedaccess, which shares features with subclasses.
Preventing Inheritance: final Classes and Methods
Marking a class final closes it: no other class may extend it. For example, to make Director the end of its branch:
public final class Director extends Manager {
. . .
}
Any attempt to extend it fails with cannot inherit from final Director.
You can also make individual methods final, so that no subclass can override them. (All methods of a final class are automatically final.)
public class Employee {
. . .
public final String getName() {
return name;
}
}
An override attempt gives getName() in Sneaky cannot override getName() in Employee; overridden method is final.
Why make something final?
The point of final is a guarantee: behavior you rely on can't be redefined by a subclass you never saw.
Stringis a final class. Nobody can define a subclass ofString, so aStringreference always refers to a genuineString, with its guaranteed immutability. That matters for security (file names, class names, URLs are strings) and for using strings as hash map keys.- Enums and records are always final.
- Immutable value classes such as
LocalDateandIntegerare final so that no subclass can add mutable state.
Overridable methods are a commitment: once others subclass your class, every non-final method becomes something they may have replaced, and you can no longer change its internal use freely. (C# and C++ take the opposite default; methods there are non-virtual unless marked.) A widely quoted guideline from Joshua Bloch's Effective Java is to design and document for inheritance, or else prohibit it.
Never call overridable methods from a constructor
If a constructor calls a method, that method should be final or private. Otherwise, a subclass can override it, and the override runs on a partially constructed object. Suppose the Employee constructor prints a description for debugging:
class Employee {
private final String name;
public Employee(String name) {
this.name = name;
System.out.println("Constructed " + description()); // calls an overridable method!
}
public String description() {
return "an employee named " + name;
}
}
Now someone adds directors with titles:
class Director extends Employee {
private final String title;
public Director(String name, String title) {
super(name);
this.title = title;
}
@Override
public String description() {
return "a director with a title of length " + title.length();
}
}
new Director("Ada", "CTO") crashes:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "this.title" is null
at Director.description(Solution.java:30)
at Employee.<init>(Solution.java:12)
The Director constructor first calls the Employee constructor, which calls description(). Because of polymorphism, that's Director.description, but the Director constructor hasn't finished yet, so title is still null.
A constructor must do enough work for the methods it calls to succeed, and that's very hard to guarantee when the methods can be overridden. So call only final or private (or static) methods from constructors. (C++ differs here: virtual calls in a constructor aren't polymorphic.)
Casting Object References
Casts between numeric types, such as (int) 7.9, convert a value. A cast between reference types doesn't convert anything; it tells the compiler to treat a reference as a more specific type, and the JVM checks that claim. Consider an array that holds both kinds of staff:
var staff = new Employee[3];
staff[0] = new Manager("Priya Nair", 91000, 2016, 4, 11);
staff[1] = new Employee("Omar Haddad", 52000, 2019, 9, 2);
staff[2] = new Employee("Lena Fischer", 46000, 2021, 6, 21);
The cast is written with the target type in parentheses:
Manager boss = (Manager) staff[0];
Storing Priya's object in an Employee[] doesn't change the object; it only means the compiler now sees it through the narrower Employee type. A cast is how you get back the Manager-specific methods, such as setBonus. (Earlier examples dodged this by calling setBonus through a Manager variable before putting the object in the array.)

The two directions differ:
- Upcast (
ManagertoEmployee): always safe, so it happens implicitly. You simply see fewer methods. - Downcast (
EmployeetoManager): may be wrong, so you must write it explicitly, and the JVM verifies it at run time.
A wrong downcast:
Manager boss = (Manager) staff[1]; // staff[1] is a plain Employee
fails with a ClassCastException:
class Employee cannot be cast to class Manager (Employee and Manager are in unnamed module of loader 'app')
If you don't catch it, the program terminates. So check before you cast, using instanceof:
if (staff[i] instanceof Manager) {
boss = (Manager) staff[i];
. . .
}
The compiler also rejects casts that can never succeed:
String c = (String) staff[i]; // error: incompatible types: Employee cannot be converted to String
String isn't a subclass of Employee, so no object could be both.
In summary:
- Between classes, you can cast only within an inheritance hierarchy. (Casts to interface types are more permissive, because a subclass of a non-final class might implement the interface; they're checked at run time, as you'll see in the interfaces part.)
- Use
instanceofto check before casting from a superclass to a subclass.
Casts are often a design smell
Most code never needs to downcast. Anything both classes support, like getSalary, already does the right thing through dynamic binding. A cast is only needed for a Manager-only method like setBonus, and if that happens all over the codebase, the hierarchy may be wrong; perhaps the operation belongs in Employee (or in an interface).
Each cast is also a place where a ClassCastException can stop the program. Minimize casts and instanceof tests, and prefer polymorphism (and, for closed hierarchies, sealed types with pattern-matching switch, coming later in this part).
Pattern Matching for instanceof
The classic test-and-cast idiom is verbose:
if (staff[i] instanceof Manager) {
Manager boss = (Manager) staff[i];
boss.setBonus(6500);
}
The type name appears three times for one idea. Since Java 16, the test can declare the variable itself:
if (staff[i] instanceof Manager boss) {
boss.setBonus(6500);
}
If staff[i] is a Manager, the pattern variable boss is set to it, typed as Manager, with no cast needed. If not, boss isn't set, instanceof yields false, and the body is skipped.
Scope of pattern variables
A pattern variable can be used wherever the compiler knows the test succeeded, which includes the rest of the same expression:
if (e instanceof Director dir && dir.getTitle().length() >= 20) . . .
This works because the right side of && is evaluated only when the left side is true, so dir is bound there. With ||, it's an error:
if (e instanceof Director dir || dir.getTitle().length() >= 20) // error: cannot find symbol dir
The right side of || runs only when the left side is false, and then nothing is bound to dir.
With the conditional operator:
String title = e instanceof Director dir ? dir.getTitle() : "(none)";
dir is defined in the expression after ?, but not in the one after :.
Pattern variables also flow into the code after a negated test:
if (!(obj instanceof String s)) return;
System.out.println(s.length()); // s is in scope here: we only get here if the test succeeded
These variable-declaring instanceof forms are called pattern matching because they're closely related to the type patterns in switch, covered in detail in the pattern matching article.
Record patterns
The example above is a type pattern: if the type matches, the object is bound to a variable. When the type is a record, Java 21 lets you go further and bind variables to the record's components. This is a record pattern:
record Point(double x, double y) { }
Object shape = . . .;
if (shape instanceof Point(var px, var py)) System.out.println(px + py);
If shape is a Point, px and py receive its x() and y() values. You can spell out the component types instead of var: shape instanceof Point(double px, double py).
Record patterns nest:
record Circle(Point center, double radius) { }
if (c instanceof Circle(Point(var a, var b), var r)) . . .
If you don't need a component, use the unnamed variable _ (preview in Java 21, final in Java 22, JEP 456):
if (shape instanceof Circle(Point(var a, var b), _)) {
System.out.println("center distance " + Math.hypot(a, b));
}
Everything Together
public class Solution {
public static void main(String[] args) {
var staff = new Employee[3];
staff[0] = new Manager("Priya Nair", 91000);
staff[1] = new Employee("Omar Haddad", 52000);
staff[2] = new Director("Ada", 120000, "Chief Technology Officer");
// cast with an explicit check
if (staff[0] instanceof Manager) {
Manager boss = (Manager) staff[0];
boss.setBonus(6500);
}
// a lying cast
try {
Manager boss = (Manager) staff[1];
} catch (ClassCastException ex) {
System.out.println(ex.getMessage());
}
// pattern matching for instanceof (Java 16)
for (Employee e : staff) {
if (e instanceof Manager m) {
m.setBonus(1000);
}
String title = e instanceof Director dir ? dir.getTitle() : "(none)";
System.out.println(e.getName() + " " + e.getSalary() + " " + title);
}
Employee x = null;
System.out.println(x instanceof Manager); // false, no exception
// record patterns (Java 21) and unnamed variables (Java 22)
Object shape = new Circle(new Point(3, 4), 1);
if (shape instanceof Circle(Point(var a, var b), _)) {
System.out.println("center distance " + Math.hypot(a, b));
}
}
}
record Point(double x, double y) { }
record Circle(Point center, double radius) { }
class Employee {
private final String name;
private final double salary;
Employee(String name, double salary) { this.name = name; this.salary = salary; }
public final String getName() { return name; } // final: can't be overridden
public double getSalary() { return salary; }
}
class Manager extends Employee {
private double bonus;
Manager(String name, double salary) { super(name, salary); }
public void setBonus(double bonus) { this.bonus = bonus; }
@Override public double getSalary() { return super.getSalary() + bonus; }
}
final class Director extends Manager {
private final String title;
Director(String name, double salary, String title) { super(name, salary); this.title = title; }
public String getTitle() { return title; }
}
class Employee cannot be cast to class Manager (Employee and Manager are in unnamed module of loader 'app')
Priya Nair 92000.0 (none)
Omar Haddad 52000.0 (none)
Ada 121000.0 Chief Technology Officer
false
center distance 5.0
Priya's bonus was first set to 6500 and then overwritten with 1000 in the loop. The director is also a manager, so she got the bonus too.
Protected Access
Fields are best private and methods usually public. Private features aren't accessible in other classes, including subclasses: Manager can't touch Employee's private salary.
Sometimes you want to make a method available to subclasses only, or (less commonly) let subclass methods access a superclass field. For that, declare the feature protected. If Employee declares
protected LocalDate startDate;
then Manager's methods can access startDate directly.
The exact rules:
- A protected feature is accessible to all classes in the same package (so it's more open than package access, not less).
- A subclass in another package can access a protected instance field or method only through references of its own type (or its subclasses), not through arbitrary superclass references.
Suppose Auditor extends Employee but lives in a different package:
package p2;
import p1.Employee;
public class Auditor extends Employee {
int ownYear() { return startDate.getYear(); } // OK: this auditor
int auditorYear(Auditor other) { return other.startDate.getYear(); } // OK: another Auditor
int otherYear(Employee other) { return other.startDate.getYear(); } // error: startDate has protected access in Employee
}
An Auditor can read the startDate of Auditor objects only, not of other Employee objects. Otherwise, anyone could create a subclass just to read protected fields of every object.
Protected fields: use with caution
If you design a class with protected fields and other programmers subclass it, they'll start using those fields, and you can no longer change your implementation without breaking their code. That's against the spirit of encapsulation. And since anyone can subclass a non-final class (or add a class to its package), a protected field is nearly as exposed as a public one.
Protected methods make more sense. A class can declare a method protected if it's tricky to use: subclasses, which presumably know their ancestor well, can be trusted with it, but other classes can't. A classic example is Object.clone (see the interfaces part). Another common pattern is the template method: a public final method defines an algorithm and calls protected "hook" methods that subclasses override.
The four access levels
| Modifier | Accessible from |
|---|---|
private | the class only |
| (none) | the package: the (unfortunate) default |
protected | the package and all subclasses |
public | the world |
From most to least restrictive: private → package → protected → public.
Common questions
Does final on a class make its objects immutable?
No. A final class can't be subclassed, but its own methods can still change its fields. Immutability needs private final fields, no mutators and defensive copies of mutable parts. final on the class just stops subclasses from adding mutable behaviour.
Can a pattern variable be reassigned?
Yes, unless you declare it final (obj instanceof final String s). Reassigning pattern variables is legal but confusing, so treat them as if they were final.
Is instanceof a code smell?
Frequent instanceof checks on your own class hierarchy often mean that a method should be overridden instead. They are fine at system boundaries, such as equals(Object) or handling values of unknown type from a framework, and in exhaustive pattern switches over sealed types, which the compiler checks.
Why can a subclass in another package not access protected fields through a superclass reference?
Otherwise anyone could write a trivial subclass just to read protected state of every object of the superclass type. The rule limits access to objects of the subclass's own type, which that subclass is responsible for.
Should I use protected fields?
Prefer private fields with protected methods, if subclasses need special access at all. Protected fields become part of your public contract with every subclass, anywhere, so you can never change them without breaking those subclasses.
Summary
- A
finalclass can't be extended; afinalmethod can't be overridden. Usefinalto protect semantics (likeString), not for speed: the JIT inlines anyway. - Never call overridable methods from constructors. Use
-Xlint:this-escapeto catch it. - Casting a reference down the hierarchy is checked at runtime and throws
ClassCastExceptionon failure. Casts between unrelated types don't compile.x instanceof Cisfalsefornull. - Prefer pattern matching (
if (e instanceof Manager m)), and record patterns such asPoint(var x, var y), with_for unused parts. Minimize casts in general. protectedmeans package + subclasses, and a subclass in another package may use protected instance members only through its own type. Prefer protected methods over protected fields.
Practice Questions
Why is java.lang.String final?
So that every String reference is guaranteed to be a real, immutable String. A subclass could add mutable state or override methods, breaking security checks, hash map keys and string interning that rely on immutability.
A superclass constructor calls an overridable init() method, and the subclass's init() uses a subclass field. What goes wrong?
The superclass constructor runs before the subclass constructor body, so the subclass's init() sees its fields with default values (null, 0). This often causes a NullPointerException. Make init() private or final, or don't call it from the constructor.
What do these do with Employee e = new Employee(...): (Manager) e; (String) e; e instanceof Manager?
(Manager) e compiles but throws ClassCastException at runtime. (String) e doesn't compile (unrelated types). e instanceof Manager evaluates to false.
Rewrite with pattern matching: if (o instanceof String) { String s = (String) o; if (s.length() > 3) print(s); }
if (o instanceof String s && s.length() > 3) print(s);
In which of these is the pattern variable in scope in the else branch: if (!(o instanceof Integer n)) { ... } else { ... }?
In the else branch. It runs only when o instanceof Integer n succeeded, so n is bound there. It's not in scope in the first branch.
Employee in package a has protected double bonusRate. Class Clerk extends Employee in package b. Can Clerk access bonusRate of another Clerk? Of a Manager?
Of another Clerk, yes: access through its own type is allowed. Of a Manager (an Employee that isn't a Clerk), no: from another package, protected instance members are accessible only through references of the subclass's own type.
Previous: Java Polymorphism and Dynamic Binding: How Method Calls Are Resolved
Related reading
- Java Polymorphism and Dynamic Binding: How Method Calls Are Resolved
- Java Inheritance: Superclasses, Subclasses and Method Overriding
- Java Class Design Hints: Writing Clean, Maintainable Classes
- Java Package Access and the Class Path
- Java Records: Compact Data Classes with Canonical and Compact Constructors

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.