Sub topic 13
Inheritance: Building on Classes
What Inheritance Is and Why It Matters
Inheritance is a way for one class to reuse the fields and methods of another class. The class being built on is called the superclass (or parent class). The class that builds on it is called the subclass (or child class).
Here is why that matters. Suppose you are writing a program about pets. Every pet has a name, and every pet can make a sound. Without inheritance, you would write the same name field and the same code in Dog, Cat, and Bird classes. That is repetitive, and if you fix a bug you have to fix it in three places.
With inheritance, you put the shared parts in one class called Pet. Then Dog, Cat, and Bird each extend Pet and add only what makes them different. You write the shared code once, and every subclass gets it automatically.
In Java, a subclass uses the keyword extends to inherit from a superclass. The word "extends" is a hint at the idea: the subclass extends what the superclass offers.
This chapter assumes you have already worked through the earlier chapters on classes, objects, fields, methods, and constructors. You should know what this means. Those ideas come back constantly here.
A few terms, defined the first time you use them:
- Superclass: the class whose fields and methods are being reused.
- Subclass: the new class that inherits from the superclass.
- Override: when a subclass provides its own version of a method it inherited, replacing the inherited version.
super: a Java keyword that refers to the superclass part of an object.
Your First Subclass
Here is a small, complete program. The Pet class is the superclass. Dog and Cat are subclasses.
class Pet {
String name;
void describe() {
System.out.println("This pet is called " + name);
}
}
class Dog extends Pet {
void fetch() {
System.out.println(name + " fetches the ball!");
}
}
class Cat extends Pet {
void purr() {
System.out.println(name + " purrs softly.");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.name = "Rex";
d.describe(); // inherited from Pet
d.fetch(); // defined in Dog
Cat c = new Cat();
c.name = "Mia";
c.describe(); // inherited from Pet
c.purr(); // defined in Cat
}
}Run this and you will see:
This pet is called Rex
Rex fetches the ball!
This pet is called Mia
Mia purrs softly.Notice two things:
Dognever mentions thenamefield, yet it can use it. It inherited that field fromPet.Dognever mentionsdescribe(), yet the calld.describe()works. It inherited that method too.
A subclass inherits all the public and protected fields and methods of its superclass. (Private members, which we will touch on below, are different.)
What a Subclass Object Really Is
Here is a mental model that will save you confusion: every subclass object contains a complete superclass object inside it. When you write new Dog(), Java builds a Dog, and inside that Dog sits a Pet part, with its own copy of the name field.
One way to picture it:
The constructor of the superclass runs as part of creating the subclass object. We will see how to control that shortly.
Overriding Methods
Often a subclass wants to change how an inherited method behaves. A generic "describe" is fine for some pets, but a dog might describe itself differently. The subclass can override the method: write a new version with the same name, same parameters, and a compatible return type.
class Pet {
String name;
void speak() {
System.out.println(name + " makes a sound.");
}
}
class Dog extends Pet {
@Override
void speak() {
System.out.println(name + " says Woof!");
}
}
class Cat extends Pet {
@Override
void speak() {
System.out.println(name + " says Meow!");
}
}
public class Main {
public static void main(String[] args) {
Pet[] pets = { new Dog(), new Cat() };
pets[0].name = "Rex";
pets[1].name = "Mia";
for (Pet p : pets) {
p.speak(); // each object runs its own version
}
}
}Output:
Rex says Woof!
Mia says Meow!The @Override on its own line is an annotation, a note for the compiler. It is optional but strongly recommended. If you spell the method name wrong or get the parameters wrong, the compiler will tell you that you are not actually overriding anything. Without the annotation, a typo like spek() would quietly create a new, unrelated method, and your pets would stop making their intended sounds.
The loop also shows something powerful. The variable p is declared as type Pet, but Java runs the version of speak() that belongs to the actual object: Dog for one element, Cat for the other. This behavior is called dynamic dispatch: the method chosen depends on the real type of the object at runtime, not the type written in the variable.
Using `super`: Calling the Superclass Version
Sometimes you do not want to replace the inherited method entirely. You want to add to it. The super keyword lets a subclass call the superclass version of a method.
class Pet {
String name;
void describe() {
System.out.println("Name: " + name);
}
}
class Dog extends Pet {
String breed;
@Override
void describe() {
super.describe(); // run Pet's version first
System.out.println("Breed: " + breed);
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.name = "Rex";
d.breed = "Labrador";
d.describe();
}
}Output:
Name: Rex
Breed: LabradorWithout super.describe(), the Dog version would never print the name line. With it, the subclass builds on the superclass behavior instead of duplicating it.
Constructors and Inheritance
Constructors are not inherited. A Dog does not get Pet's constructor just by extending Pet. But the superclass's constructor does run when you create a subclass object, because the Pet part inside the Dog needs to be set up.
Java handles this automatically in the common case. If the superclass has a constructor with no parameters, and the subclass constructor does not call it explicitly, Java inserts the call for you.
If the superclass only has a constructor that takes parameters, the subclass must call it explicitly using super(...) as the first statement in its constructor:
class Pet {
String name;
Pet(String name) {
this.name = name;
System.out.println("Pet constructor ran for " + name);
}
}
class Dog extends Pet {
String breed;
Dog(String name, String breed) {
super(name); // must be the first statement
this.breed = breed;
System.out.println("Dog constructor ran, breed is " + breed);
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog("Rex", "Labrador");
}
}Output:
Pet constructor ran for Rex
Dog constructor ran, breed is LabradorTwo rules to remember:
super(...)must be the very first statement in the subclass constructor.- If the superclass has no constructor with zero parameters, every subclass constructor must call
super(...)explicitly, or the code will not compile.
What Is Not Inherited: Private Members
A private field or method belongs to the superclass's own code. The subclass inherits the memory for private fields (the data exists inside each object), but the subclass's code cannot access it directly. It must go through public or protected methods.
This matters for a habit you should build: make fields private and expose them through methods. Subclasses then interact with the superclass through its public interface, just like any other code does.
class Pet {
private String name; // private: not directly visible to subclasses
Pet(String name) {
this.name = name;
}
public String getName() {
return name; // Pet's own code can use it
}
}
class Dog extends Pet {
Dog(String name) {
super(name);
}
void greet() {
// System.out.println(name); // would NOT compile
System.out.println("Hi, I am " + getName()); // must use the method
}
}If you delete the comment markers on the direct access line, the compiler will reject the file with an error like "name has private access in Pet."
Common Errors and How to Fix Them
Beginners hit the same handful of problems with inheritance. Here they are, with fixes:
| Error | What it looks like | Fix |
|---|---|---|
| Forgot `extends` | Inherited methods "do not exist" on the subclass | Add `extends SuperclassName` to the class declaration |
| Method does not override | New method runs, old behavior still appears elsewhere | Match the name and parameters exactly; add `@Override` to catch typos |
| Missing `super(...)` call | Compiler error: "constructor Pet cannot be applied" | Call `super(arguments)` as the first line of the subclass constructor |
| Accessing a private field | "name has private access in Pet" | Use a public getter method instead |
| Wrong constructor call order | `super(...)` not on the first line causes a compile error | Move `super(...)` to be the first statement |
One more subtle trap: calling an overridable method from the superclass constructor. If Pet's constructor calls speak(), and Dog overrides speak(), the Dog version runs before the Dog constructor has finished. Its own fields may not be set yet. Avoid calling methods that subclasses might override from a constructor.
How Inheritance Fits the Rest of Java
Inheritance is everywhere in Java's own library, and recognizing it will help you read real code. Every class you write automatically extends a class called Object, the ancestor of all Java classes. That is why every object has methods like toString() — you inherited them from Object, and you can override toString() to give any class a nicer printed form.
Inheritance is also the foundation for interfaces and polymorphism (using one variable type to hold many object types, as we did with the Pet[] array). Those topics get their own treatment elsewhere; here you only need the mechanics.
A quick guideline on when to use inheritance: use it when the subclass truly is a kind of the superclass. A dog is a pet, so Dog extends Pet makes sense. If the relationship is "has a" (a car has an engine), prefer holding one object as a field inside another instead of inheriting.
Key Takeaways
- Inheritance lets a subclass reuse the fields and methods of a superclass with
extends. - Every subclass object contains a full superclass object inside it; superclass constructors run as part of object creation.
- Subclasses can override inherited methods;
@Overridecatches typos. super.method()calls the superclass version;super(args)in the constructor must be the first statement.- Private members are not directly accessible to subclass code; use public methods.
- Every class implicitly extends
Object. - Use inheritance for "is a" relationships; use a field for "has a" relationships.
Exercise
In the chapter's first example, why does the call d.describe() work even though the Dog class has no describe method?
Show answer
Dog extends Pet, so it inherits Pet's public methods. describe() is defined in Pet, so every Dog object can call it. In memory, each Dog contains a Pet part holding the name field and the describe method.
Exercise
What is wrong with this constructor, and how do you fix it? class Dog extends Pet { Dog(String name, String breed) { this.breed = breed; super(name); } }
Show answer
The super(...) call must be the first statement in the constructor. Move it: super(name); then this.breed = breed;
Exercise
A subclass overrides speak() but misspells it as spek(). What happens, and how would you catch the mistake?
Show answer
The compiler accepts it and creates a new, unrelated method called spek(). Objects would keep running the superclass's speak(). Adding @Override above the method makes the compiler fail with an error, because spek() does not actually override anything.