Junior — Middle
Can a child class access private properties of the base class?
sobes.tech AI
Answer from AI
In Java, a child class cannot directly access the private properties of the superclass. Private fields are only accessible within the class where they are declared. To access such fields from a subclass, protected or public getter/setter methods are usually used. For example:
class Parent {
private int secret = 42;
protected int getSecret() {
return secret;
}
}
class Child extends Parent {
void showSecret() {
// System.out.println(secret); // Compilation error
System.out.println(getSecret()); // Correct
}
}