Sub topic 1
Subclasses and Inheritance: The Starting Point
Building on an Existing Class
Inheritance is a way to make a new class from an existing one. The new class is called a subclass. The class it builds on is called the superclass. In Java, you use the keyword extends to make a subclass.
A subclass gets the methods and fields of its superclass for free. It can also add new ones.
class Animal {
String sound() {
return "...";
}
}
class Dog extends Animal {
@Override
String sound() {
return "Woof";
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a.sound()); // prints Woof
}
}One Variable, Many Kinds of Objects
Look at the line Animal a = new Dog();. It involves two types:
- The declared type is the type written on the variable. Here it is
Animal. - The runtime type is the class of the actual object. Here it is
Dog.
Java allows this because every Dog is also an Animal. Storing a subclass object in a superclass variable is called upcasting. One Animal variable can hold a Dog, a Cat, or any other subclass.
Overriding a Method
Method overriding means a subclass writes its own version of a method it inherited. The method must have the same name and the same parameters as the superclass method.
Dog overrides sound(). When you call a.sound(), Java runs the version that belongs to the object's runtime type, Dog. That is why the program prints Woof and not ....
Letting the Compiler Check You with @Override
@Override is an annotation, which is a label you put above a method. It tells the compiler, "I mean to override a superclass method."
Suppose you make a typo and write sounds() instead of sound(). Without @Override, Java quietly treats sounds() as a brand-new method. Your override never runs, and you get no warning. With @Override, the compiler sees that the superclass has no sounds() method and stops with an error.
Exercise
In the line Animal pet = new Dog();, what is the declared type, what is the runtime type, and what does pet.sound() return?
Show answer
The declared type is Animal and the runtime type is Dog. pet.sound() returns "Woof" because Java runs the Dog version of the overridden method.
Exercise
You add a method String Sound() (capital S) to Dog and mark it with @Override. What happens?
Show answer
The code does not compile. Java names are case-sensitive, so Animal has no method called Sound(), and @Override reports that nothing is being overridden.