Inheritance (extends)
A class can inherit fields and methods from another class with extends — reusing code.
What you will learn
- Create a subclass with extends
- Reuse and add to the parent class
- Use super to call the parent
Sharing common code
Often classes share things. A Dog and a Cat are both Animals — both have a name and can eat. Rather than repeat that, one class can inherit from another using extends.
The class you inherit from is the parent (or superclass). The class that inherits is the child (or subclass). The child gets all the parent fields and methods for free, then can add its own.
public class Animal {
String name;
void eat() {
System.out.println(name + " is eating.");
}
}
public class Dog extends Animal {
void bark() {
System.out.println(name + " says woof!"); // name comes from Animal
}
}Note: Output: (No output yet — these are the classes. Notice Dog never declares name or eat(), yet it can use them because it inherited them from Animal.)
Using the inherited members
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.name = "Rex";
d.eat(); // inherited from Animal
d.bark(); // Dog's own method
}
}Note: Output:
Rex is eating.
Rex says woof!
eat() came from the Animal parent, while bark() is Dog own. One Dog object happily uses both. That is code reuse through inheritance.
The keyword super
A child can call the parent constructor or methods with super. This is common in constructors:
public class Animal {
String name;
Animal(String name) { this.name = name; }
}
public class Dog extends Animal {
Dog(String name) {
super(name); // call Animal's constructor
}
}Note: Output:
(No output — this shows the pattern. super(name) runs the Animal constructor first, so the inherited name field gets set correctly.)
Tip: A good test for inheritance is the words is a. A Dog is an Animal, so Dog extends Animal makes sense. If you cannot say is a, inheritance is probably the wrong tool.
Q. If Dog extends Animal and Animal has a method eat(), can a Dog object call eat()?
✍️ Practice
- Create a
Vehicleclass with astart()method, and aCarsubclass that addshonk(). - Make a Car object and call both methods.
🏠 Homework
- Build a
Shapeparent class and two children (Circle, Square) that each add their own method. Show one object of each.