Sub topic 1
Subclasses and Inheritance: The Starting Point
Polymorphism means "many forms." In Java, it lets one piece of code work with many kinds of objects. Before you can use it, you need the idea it rests on: inheritance. This chapter explains what inheritance is, how to write it in Java, and the rules that come with it. Later chapters build on this base.
This chapter assumes you can write a class, create an object with new, and run a small Java program.
What Inheritance Is
Inheritance is a way to build a new class from an existing class. The new class gets the fields and methods of the old one for free. It can then add its own.
Two terms come up again and again:
- A superclass is the class you build from. It is also called the parent or base class.
- A subclass is the new class built from it. It is also called the child or derived class.
Why does this matter? Many classes share common parts. A dog, a cat, and a bird all have a name and all eat. Without inheritance, you would copy the same code into each class. If you then found a bug, you would have to fix it in every copy. With inheritance, you write the shared code once in a superclass, and every subclass reuses it.
The extends Keyword
In Java, you make a subclass with the keyword extends. A keyword is a word with a fixed meaning in the language. class Dog extends Animal means "Dog is a new class built from Animal."
Here is a complete program. Save it as Main.java.
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 rex = new Dog();
rex.name = "Rex";
rex.eat();
rex.bark();
}
}Run it with java Main.java (Java 11 or later). The output is:
Rex is eating.
Rex says Woof!Look at what happened:
Dognever declares anamefield, butrex.nameworks.Doginherited it fromAnimal.Dognever declareseat(), butrex.eat()works. That method is inherited too.bark()exists only inDog. AnAnimalobject would not have it.
A subclass gets everything its superclass offers and can add more on top.
Drawing the Family Tree
Classes linked by extends form a tree. Each subclass points up to its superclass.
The arrow points from the subclass to its superclass. Dog and Cat both share Animal's name and eat(). Each also adds a method of its own.
The "Is-A" Test
How do you know if inheritance fits? Use the is-a test. Say the sentence "A subclass is a superclass." If it sounds true, inheritance may be a good fit.
| Sentence | True? | Use inheritance? |
|---|---|---|
| A Dog is an Animal. | Yes | Yes: `Dog extends Animal` |
| A SavingsAccount is an Account. | Yes | Yes: `SavingsAccount extends Account` |
| A Car is an Engine. | No | No. A Car *has* an Engine, so give Car a field of type Engine. |
| A Stack is a Color. | No | No. They are unrelated. |
The "has-a" case is common. When one thing contains another, use a field, not extends. Using a field this way is called composition.
This test matters for polymorphism. Because a Dog is an Animal, Java lets you use a Dog anywhere it expects an Animal. The next chapter shows how.
Constructors and super(...)
A constructor is the special method that sets up a new object. It has the same name as the class. Constructors are not inherited. Each class writes its own.
But a subclass object contains a superclass part, and that part must be set up too. So every subclass constructor first runs a superclass constructor. You choose which one with super(...).
This version also makes name private. A private member can only be used inside the class that declares it.
class Animal {
private final String name;
Animal(String name) {
this.name = name;
System.out.println("Animal constructor runs");
}
String getName() {
return name;
}
void eat() {
System.out.println(name + " is eating.");
}
}
class Dog extends Animal {
private final String breed;
Dog(String name, String breed) {
super(name);
this.breed = breed;
System.out.println("Dog constructor runs");
}
void describe() {
System.out.println(getName() + " is a " + breed + ".");
}
}
public class Main {
public static void main(String[] args) {
Dog rex = new Dog("Rex", "Beagle");
rex.describe();
rex.eat();
}
}Output:
Animal constructor runs
Dog constructor runs
Rex is a Beagle.
Rex is eating.Notice three things:
super(name)passes the name up toAnimal's constructor. TheAnimalpart is built first, then theDogpart.Dogcannot writethis.nameornamedirectly, becausenameis private toAnimal. The field still exists inside every Dog object.Dogreaches it through the public-facing methodgetName().eat()still works on a Dog, because it is inherited and is not private.
What Gets Inherited
Here is a summary of what a subclass receives.
| Member of the superclass | Inherited? | Can the subclass use it by name? |
|---|---|---|
| Public or package-level field or method | Yes | Yes |
| `protected` field or method | Yes | Yes, even from another package |
| `private` field or method | Exists in the object, but not accessible | No, use a non-private method instead |
| Constructor | No | Only by calling `super(...)` |
Package-level (no modifier) means visible to classes in the same package. A package is a named group of related classes. All the examples in this chapter sit in one file, so they share a package.
Every Class Extends Object
What if a class has no extends? Java treats it as if it said extends Object. Object is a built-in class at the very top of every class tree. That is why the diagram above shows it.
This means every object inherits methods such as toString() and equals() from Object. Try this inside main:
Dog rex = new Dog("Rex", "Beagle");
System.out.println(rex.toString());It prints something like Dog@1b6d3586. That is Object's default text: the class name, an @, and a hex code. The exact code differs from run to run. A later chapter shows how to replace it with something useful.
Limits on Inheritance
Java puts two limits on extends:
- Single inheritance. A class can extend only one superclass.
class Dog extends Animal, Petdoes not compile. (Java offers interfaces for sharing behavior across unrelated classes. They get their own chapter.) - Final classes. A class marked
finalcannot be extended.Stringis final, soclass MyString extends Stringfails to compile.
A chain of inheritance is fine, though. If Puppy extends Dog and Dog extends Animal, a Puppy inherits from both Dog and Animal.
Looking Ahead
So far, subclasses only add methods. The real power comes when a subclass replaces an inherited method with its own version. That is called overriding. Combined with the is-a idea, it lets Java run different code for a Dog and a Cat through the same line of code. The next chapters build up to that, step by step.
Exercise
Write a class Cat that extends the second version of Animal (the one with a constructor that takes a name). Give Cat a constructor Cat(String name) and a method meow() that prints the cat's name followed by " says Meow!". What must the first line of Cat's constructor be, and why?
Show answer
The first line must be super(name);. Animal has no constructor without parameters, so Cat must call Animal(String name) to build the Animal part of the object. A working version is: class Cat extends Animal { Cat(String name) { super(name); } void meow() { System.out.println(getName() + " says Meow!"); } }. It uses getName() because name is private in Animal.
Exercise
Apply the is-a test. Which of these should use extends? (a) Truck and Vehicle, (b) Library and Book, (c) Manager and Employee.
Show answer
(a) Yes, a Truck is a Vehicle, so Truck extends Vehicle. (b) No, a Library has Books, so Library should hold a field such as a list of Book objects (composition). (c) Yes, a Manager is an Employee, so Manager extends Employee.
Exercise
Given class A { A() { System.out.println("A"); } } and class B extends A { B() { System.out.println("B"); } }, what does new B(); print?
Show answer
It prints A and then B on separate lines. B's constructor has no explicit super(...), so Java inserts super() automatically. That runs A's constructor first, and then the rest of B's constructor runs.