Sub topic 1
Create a Subclass with extends
Many programs have classes that are alike. A Dog and a Cat both eat and sleep. Writing the same code twice is tedious and easy to get wrong. Java solves this with inheritance. In this chapter you will learn what inheritance is and how to write your first subclass with the extends keyword.
This chapter assumes you can write a simple Java class with fields, methods, and constructors. It also assumes you know the basic access modifiers (public, private) and can compile and run a Java program.
What Inheritance Means
Inheritance is a way for one class to reuse the members of another class. Members are the fields and methods a class contains. The class that gives its members away is the superclass. The class that receives them is the subclass. You may also hear "parent class" and "child class". They mean the same thing.
Inheritance models an "is-a" relationship. A dog is an animal. A car is a vehicle. A savings account is a bank account. If "X is a Y" sounds right, X may be a good subclass of Y.
Inheritance gives you three benefits:
- Reuse. You write shared code once, in the superclass.
- Specialization. The subclass adds its own members or changes inherited behavior.
- Substitution. Code written for the superclass can also work with any subclass. A later chapter covers this idea, called polymorphism.
The extends Keyword
You create a subclass by writing extends and the superclass name after the subclass name:
class SubclassName extends SuperclassName {
// members that belong only to the subclass
}The extends keyword tells the compiler: "This class starts with everything the superclass offers. I will add more."
A First Worked Example
Here is a superclass named Animal and a subclass named Dog.
class Animal {
void eat() {
System.out.println("The animal eats.");
}
void sleep() {
System.out.println("The animal sleeps.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.sleep();
dog.bark();
}
}Save this as Main.java. Compile it with javac Main.java and run it with java Main. The output is:
The animal eats.
The animal sleeps.
Woof!Look at what happened. The Dog class declares only bark(). Yet dog.eat() and dog.sleep() work, because Dog inherited them from Animal. You wrote those two methods once, and every future subclass can use them.
Only one file in a program may be public and named after the file. That is why Main is public and Animal and Dog are not.
Drawing the Relationship
Inheritance diagrams usually put the superclass at the top. An arrow with a hollow head points from each subclass up to its superclass. Mermaid's class diagram draws this relationship with <|--.
Several subclasses can share one superclass. A class can have a long chain of ancestors too. If Puppy extends Dog and Dog extends Animal, then Puppy gets members from both Dog and Animal.
A Subclass Is a Kind of Its Superclass
Because a Dog is an Animal, Java lets you store a Dog object in an Animal variable. No special syntax is needed.
class Animal {
void eat() {
System.out.println("The animal eats.");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Meow!");
}
}
public class Main {
public static void main(String[] args) {
Animal pet = new Cat();
pet.eat();
// pet.meow(); // would not compile: Animal has no meow()
if (pet instanceof Cat) {
Cat cat = (Cat) pet;
cat.meow();
}
}
}This is a separate program, so save it in its own Main.java. The output is:
The animal eats.
Meow!There are two ideas here.
- The variable type decides which methods you may call.
petis declared asAnimal, so the compiler only lets you use whatAnimaloffers. The object is really aCat, but the compiler checks the variable's type, not the object. - To go back down to the subclass, you need a cast. A cast is a type name in parentheses, such as
(Cat). It tells the compiler "trust me, this is really aCat." If you are wrong, the program fails at run time with aClassCastException. Theinstanceofoperator checks first, so it is a safe guard.
The other direction never needs a cast. Moving from a subclass up to a superclass is always safe.
What a Subclass Can Do
A subclass can do four things:
- Use inherited members as if it had declared them.
- Add new fields and methods.
- Provide its own version of an inherited method. This is called overriding, and it has its own chapter.
- Declare constructors of its own.
The next chapter looks closely at which members are inherited and which are hidden by access rules.
The Rules of extends
These rules cover most beginner situations.
- A class extends exactly one class. Java has single inheritance for classes. Writing
class Dog extends Animal, Petis a compile error. Interfaces give you a way to combine several types, which a later chapter explains. - Every class already has a superclass. If you write no
extends, Java quietly makes your class extendjava.lang.Object. So every class in Java is part of one big family tree withObjectat the top. - Cycles are not allowed.
A extends Btogether withB extends Awill not compile. - A
finalclass cannot be extended.Stringis an example. A later chapter shows how to mark your own classesfinal. - Constructors are not inherited. A subclass does not get its superclass's constructors. Instead, every subclass constructor must call one. The chapter on constructor chaining covers this.
Rule 5 can cause a surprise even in a simple program. Suppose the superclass has only a constructor that takes a parameter:
class Animal {
private final String name;
Animal(String name) {
this.name = name;
}
}
class Dog extends Animal {
// no constructor written here
}This does not compile. A class with no constructor gets a default one that tries to call Animal(). That constructor does not exist. The compiler reports an error like this:
error: constructor Animal in class Animal cannot be applied to given types;The fix is to write a Dog constructor that calls super(name). You will learn that in the chapter on super(...). For now, remember that extends alone is not enough when the superclass has no no-argument constructor.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `class A extends B, C` | Compile error: only one class after `extends` | Pick one superclass. Use interfaces for the rest. |
| Using `implements` with a class | Compile error: a class is not an interface | Use `extends` for classes. |
| Extending a `final` class | Compile error: cannot inherit from final class | Choose another design, or remove `final` from your own class. |
| Calling a subclass method through a superclass variable | Compile error: method not found | Cast to the subclass, after checking with `instanceof`. |
| Extending only to reuse code, with no "is-a" link | Code compiles but the design is confusing | Hold the other class in a field instead. See the chapter on composition. |
Choosing Good Subclasses
Before you write extends, ask a short test question: "Is every object of my new class also a valid object of the old class?"
- A
Dogis anAnimal. Inheritance fits. - A
Caris not anEngine. A car has an engine. Use a field, notextends. - A
Stackis not truly anArrayList, even though both hold items. Extending would expose methods a stack should not have.
Passing the "is-a" test is a good start, not a guarantee. You will meet more design questions in the last chapter of this tutorial.
Summary
- Inheritance lets a subclass reuse and specialize a superclass.
class Sub extends Supercreates the relationship.- A subclass has the inherited members plus its own.
- A class can extend only one class, and every class ultimately extends
Object. - A subclass object can be stored in a superclass variable, but only the superclass's members are visible through it.
- Constructors are not inherited, and a missing no-argument superclass constructor causes a compile error.
Exercise
You write class Car extends Vehicle. Vehicle declares void start() and Car declares void honk(). Which of these calls work on Car car = new Car();: car.start(), car.honk()? What about Vehicle v = new Car(); v.honk();?
Show answer
Both car.start() and car.honk() work, because Car inherits start() from Vehicle and declares honk() itself. v.honk() does not compile, because the variable type is Vehicle and Vehicle has no honk() method. To call it, check with instanceof and cast: ((Car) v).honk();.
Exercise
A classmate writes class Robot extends Machine, Toy. What is wrong, and what is one Java feature that helps with the goal?
Show answer
A Java class can extend only one class, so the compiler rejects two names after extends. Interfaces help here. A class can extend one class and implement several interfaces, for example class Robot extends Machine implements Toy.
Exercise
Which relationship is a poor fit for extends: Circle and Shape, Library and Book, or Manager and Employee? Explain with the "is-a" test.
Show answer
Library and Book is the poor fit. A library is not a kind of book. It has books, so it should hold them in a field, such as a list. Circle is a Shape and Manager is an Employee, so both pass the test.