Sub topic 1
Create a Subclass with extends
Create a subclass
A class is a plan for making objects. An object is a particular thing made from a class.
A subclass is a class based on another class. The class it is based on is its superclass. In Java, extends creates this relationship. For example, Dog extends Animal means that Dog is a kind of Animal.
Understand inherited members
A method is an action an object can perform. A subclass inherits, or gets, accessible methods from its superclass. It can use them without writing them again.
In the example below, Dog inherits the rest method from Animal. Some members are not directly accessible in a subclass. For example, a field marked private cannot be used directly there.
Override superclass methods
A subclass can provide its own version of an inherited method. This is called overriding. In the example, Dog overrides speak.
@Override asks Java to check that speak really overrides a superclass method. It helps catch mistakes, such as a misspelled method name.
Save this program as Main.java:
class Animal {
String speak() {
return "Animal sound";
}
String rest() {
return "Resting";
}
}
class Dog extends Animal {
@Override
String speak() {
return "Woof";
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
System.out.println(animal.speak());
System.out.println(animal.rest());
}
}String is Java’s type for text. Both methods return text, which println prints.
Compile and run the program:
javac Main.java
java MainIt prints Woof, then Resting on the next line.
Use subtypes and understand method dispatch
A subtype is a more specific type that can be used where a more general type is expected. Dog is a subtype of Animal, so an Animal variable can refer to a Dog object.
A reference is a value that lets code use an object. Although the reference animal has type Animal, the actual object is a Dog. When animal.speak() runs, Java chooses the Dog version. This choice is called dynamic dispatch.
The call to rest() uses the method inherited from Animal, because Dog does not override it.
Exercise
If Dog did not override speak, what would animal.speak() print?
Show answer
It would print Animal sound, using the method inherited from Animal.