Java MCQ: Can a subclass inherit private members of its superclass?
Answer:
Explanation:
In Java, a subclass cannot inherit private members (fields and methods) of its superclass. Private members are only accessible within the class in which they are declared, meaning they cannot be accessed directly by subclasses or other classes outside the defining class. This restriction is a key aspect of encapsulation, one of the fundamental principles of Object-Oriented Programming (OOP), which ensures that the internal implementation details of a class are hidden from the outside world.
However, a subclass can indirectly access private members of the superclass through public or protected methods that the superclass provides. For instance, a superclass might provide a public getter method to allow controlled access to a private field:
class Animal {
private String name;
Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
void display() {
System.out.println("Dog name is: " + getName());
}
}
In this example, the Dog
class cannot directly access the private name
field of the Animal
class. However, it can use the public getName()
method provided by Animal
to retrieve the value of name
. This approach allows the superclass to control how its private members are accessed, ensuring that they are not exposed or modified in unintended ways.
Understanding this aspect of inheritance helps in designing secure and well-encapsulated classes in Java, where the internal state of an object is protected from unauthorized access and modification.