Unit 3 Cycle 2 Day 9: Error: Accessing Private Parent Fields

Unit 3 Advanced (Cycle 2) Day 9 of 28 Advanced

Error: Accessing Private Parent Fields

Section 3.9 — Scope and Access

Key Concept

A subclass cannot directly access private fields of its superclass, even though those fields exist in the subclass object. The code super.privateField does not compile because private means private to the declaring class only. The subclass must use inherited public accessor methods to read or modify the superclass's private state. The AP exam creates error-spotting questions where a subclass method tries to read or assign a private superclass field directly. The fix is always to use the getter or setter.

Consider the following classes.

public class Person { private String name; public Person(String n) { name = n; } public String getName() { return name; } } public class Student extends Person { private int grade; public Student(String n, int g) { super(n); grade = g; } public String info() { return name + " grade " + grade; } }

What happens when this code is compiled?

Answer: (B) Compile error in info(): name is private in Person.

name is private in Person. Even though Student extends Person, it cannot access private fields directly. Student must use getName() instead of name.

Why Not the Others?

(A) The code does not compile due to the private access violation.

(C) This is caught at compile time, not runtime.

(D) The constructor correctly uses super(n) and is valid.

Common Mistake

Private means private to the class, even from subclasses. A subclass must use public accessors to read parent data. The fix: return getName() + " grade " + grade;.

AP Exam Tip

Subclasses CANNOT access private parent fields directly. They must use public getters. This is a core encapsulation rule tested on the AP exam.

Review this topic: Section 3.9 — Scope and Access • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.