Sub topic 13
Inheritance: Building on Classes
What Inheritance Is
Inheritance is a way for one class to get the fields and methods of another class for free. The class you start from is called the superclass (or parent class). The class you build on top of it is called the subclass (or child class).
You write extends to create a subclass. Here, Dog extends Animal:
class Animal {
String name;
void eat() {
System.out.println(name + " is eating.");
}
}
class Dog extends Animal {
void bark() {
System.out.println(name + " says Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.name = "Rex";
d.eat(); // inherited from Animal
d.bark(); // defined in Dog
}
}Output:
Rex is eating.
Rex says Woof!Dog did not define eat, yet d.eat() works. The subclass inherits everything the superclass has (except private members, which stay hidden).
Why It Matters
Inheritance removes duplicated code. If you add a Cat class, it can also extend Animal and get eat without rewriting it. Behavior you fix in Animal is fixed everywhere at once.
flowchart TD
Animal["class Animal<br/>name, eat()"] --> Dog["class Dog<br/>bark()"]
Animal --> Cat["class Cat<br/>meow()"]caption: Two subclasses extend one superclass, sharing its fields and methods. alt: A box labeled Animal points to boxes labeled Dog and Cat, showing both inherit from Animal.
Overriding Methods
A subclass can replace an inherited method with its own version. This is called overriding. The new method must have the same name, parameters, and return type.
class Animal {
String name;
void speak() {
System.out.println(name + " makes a sound.");
}
}
class Cat extends Animal {
@Override
void speak() {
System.out.println(name + " says Meow.");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Animal();
a.name = "Generic";
a.speak();
Cat c = new Cat();
c.name = "Milo";
c.speak();
}
}Output:
Generic makes a sound.
Milo says Meow.@Override is an annotation (a label for the compiler). It is optional but recommended: if you misspell the method name, the compiler warns you instead of silently creating a new method.
The super Keyword
Sometimes you want to keep the superclass version and add to it. The super keyword calls the superclass's method from inside the subclass.
class Cat extends Animal {
@Override
void speak() {
super.speak(); // first do what Animal does
System.out.println("...Meow!"); // then add more
}
}Now speak() on a Cat prints both lines.
What Subclasses Do Not Inherit
- Constructors are not inherited, though a subclass can call one with
super(...)as its first statement. - Private fields and methods are not directly accessible in the subclass.
- Final classes cannot be extended at all:
final class Point { }means "no subclasses."
Common Errors
- Wrong method signature when overriding.
void speak(String s)does not overridevoid speak(). Use@Overrideto catch this. - Forgetting
extends. Writingclass Dog { }instead ofclass Dog extends Animal { }gives you no inherited members. - Expecting private access. If
Animalhad a privatename,Dogcould not use it directly.
Inheritance Versus Composition
Inheritance means "is a": a Dog is an Animal. When the relationship is "has a" (a Car has an Engine), store an object as a field instead of extending. Picking the right relationship keeps designs clean.
Exercise
What is the output when a Cat object created in this chapter's overriding example calls speak()?
Show answer
"Milo says Meow." — the Cat class overrides Animal's speak method, so the Cat version runs instead.
Exercise
How would you call Animal's original speak() from inside Cat's overridden speak()?
Show answer
Call super.speak(); as the first line of Cat's speak method.