Sub topic 1
Create a Subclass with extends
Inheritance is a way to build a new class from an existing one. The existing class is called the superclass. The new class is called the subclass. The subclass gets the fields and methods of the superclass without you copying them. You use the word extends to connect the two.
Think of a dog. A dog is an animal. It eats and sleeps like other animals. It also barks, which other animals may not do. In Java, you can model this idea by making Dog a subclass of Animal.
Writing a Subclass
A class is a blueprint for objects. A method is a named block of code inside a class. To make a subclass, add extends and the name of the superclass after the new class name.
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("The dog barks: Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.bark(); // defined in Dog
dog.eat(); // inherited from Animal
dog.sleep(); // inherited from Animal
}
}When you run this program, it prints:
The dog barks: Woof!
The animal eats.
The animal sleeps.The Dog class has only one method of its own, bark(). Yet a Dog object can also call eat() and sleep(). Those methods are inherited, which means the subclass receives them from the superclass.
The diagram below shows the relationship. The arrow points from the subclass to the superclass.
What Inheritance Gives You
A subclass gets these things from its superclass:
- Methods that the superclass defines
- Fields that the superclass defines, with the access rules covered later in this chapter series
- The ability to be used anywhere the superclass is expected
You can also add new methods and fields to the subclass. This is how the subclass becomes more specific than its superclass.
Inheritance saves you from repeating code. If you add a new method to Animal, every Dog gets it too.
> Java allows only one superclass for each class. A class can extend one class, but not two.
The note above is a warning. Here is how it looks as a callout.
Try It
Exercise
Suppose you write class Cat extends Animal and create a Cat object named kitty. Can kitty call eat()?
Show answer
Yes. Cat extends Animal, so Cat inherits eat() from Animal. You can write kitty.eat() without writing a new eat() method in Cat.
Exercise
Why does the Main class in the example call dog.eat() even though Dog never defines eat()?
Show answer
Because Dog extends Animal, and Animal defines eat(). The subclass inherits the method, so the Dog object can use it.