Public Inheritance and Access Control
You'll learn: How public members behave when inherited and the visibility implications of exposing inherited APIs through public inheritance.
The Core Idea
When a class publicly inherits from another class (which is the default and only type of inheritance in Java), all public members of the superclass remain public in the subclass. This creates a powerful but important responsibility: your subclass automatically exposes the entire public API of its parent to the outside world.
Think of it like a franchise business. If a local restaurant franchises under a famous brand, customers expect access to all the standard menu items (the public API). The franchise can add new items, but it can't hide the core offerings—they're part of the brand's public identity.
Visibility Implications
package animals;
public class Animal {
public void eat() {
System.out.println("Eating...");
}
public void sleep() {
System.out.println("Sleeping...");
}
}
package animals;
public class Dog extends Animal {
public void bark() {
System.out.println("Woof!");
}
}
package main;
import animals.Dog;
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Accessible! Inherited public method
dog.sleep(); // Accessible! Inherited public method
dog.bark(); // Accessible! Dog's own public method
}
}
The Dog class automatically exposes eat() and sleep() because they're public in Animal. Anyone using a Dog can call these inherited methods—there's no way to "hide" them through inheritance.
Design Consideration
Be thoughtful about what you inherit from. Every public member in your superclass becomes part of your class's contract with the outside world.
Key Takeaway: Public members inherited from a superclass remain public in all subclasses, automatically expanding your class's visible API to include the parent's entire public interface.