Inheriting Methods from a Superclass
What you'll learn: How subclasses automatically gain access to all non-private methods from their superclass and can use them as if they were defined locally.
When a class inherits from a superclass using extends, it doesn't just gain the fields—it also inherits all the superclass's non-private methods. This means your subclass can call these methods directly, without needing to rewrite them.
How Method Inheritance Works
Just like fields, any method with public, protected, or package-private (default) access in the superclass becomes available to the subclass. The subclass treats these inherited methods as if they were part of its own definition.
Think of it like inheriting family skills: if your parent knows how to cook, you can use that knowledge without having to learn it from scratch yourself.
Example
class Animal {
public void breathe() {
System.out.println("Inhaling and exhaling");
}
public void sleep() {
System.out.println("Sleeping...");
}
}
class Dog extends Animal {
// Dog inherits breathe() and sleep()
// No need to redefine them!
}
// Usage:
Dog myDog = new Dog();
myDog.breathe(); // Calls the inherited method from Animal
myDog.sleep(); // Also inherited from Animal
The Dog class doesn't define breathe() or sleep(), but it can call them because they're inherited from Animal. The methods work exactly as they do in the superclass.
What Gets Inherited?
- ✅
publicmethods - ✅
protectedmethods - ✅ Package-private methods (if subclass is in same package)
- ❌
privatemethods (not accessible to subclass)
Key Takeaway: Subclasses automatically inherit all non-private methods from their superclass and can call them directly, promoting code reuse without duplication.