Java Inheritance
Many things share common features. A car and a bike are both vehicles; a teacher and a student are both people. Inheritance lets a new class take over the fields and methods of an existing class and add its own. The existing class is the superclass (or parent), and the new one is the subclass (or child). It is written with the keyword extends.
extends
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 d = new Dog();
d.name = "Rocky";
d.eat();
d.bark();
}
}Rocky is eating. Rocky says woof!
Dog has no name field and no eat method of its own, but it inherits both from Animal. A dog is an animal, which is the test for whether inheritance fits: use it only when the "is a" sentence is true.
Constructors and super
A subclass constructor must first set up the superclass part. It does that by calling super(...) as its first statement:
class Person {
protected String name;
Person(String name) {
this.name = name;
}
String introduce() {
return "I am " + name + ".";
}
}
class Teacher extends Person {
private String subject;
Teacher(String name, String subject) {
super(name);
this.subject = subject;
}
@Override
String introduce() {
return super.introduce() + " I teach " + subject + ".";
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person("Arjun");
Teacher t = new Teacher("Ms. Rao", "physics");
System.out.println(p.introduce());
System.out.println(t.introduce());
}
}I am Arjun. I am Ms. Rao. I teach physics.
protectedmakesnameusable in subclasses (see Modifiers).Teacheroverridesintroduce: it gives its own version of an inherited method.super.introduce()calls the superclass's version, so the teacher's text builds on it.@Overrideasks the compiler to check that the method really overrides one. A typing mistake in the name then becomes an error instead of a silent new method.
Every class extends Object
A class without extends automatically extends Object, the root of all classes. That is where toString comes from: your toString methods override Object.toString, which is public, and an override may not be less visible, which is why yours must be public too.
class Plain {
}
class Named {
@Override
public String toString() {
return "a Named object";
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Named());
System.out.println(new Plain().toString().startsWith("Plain@"));
}
}a Named object true
Stopping inheritance
A class marked final cannot be extended; String is such a class. A method marked final cannot be overridden. Java also allows only one superclass per class; to share behaviour across unrelated classes it uses Interfaces instead.
The next topic, Polymorphism, shows the biggest benefit of inheritance: treating different subclasses in the same way.
Practice exercises
- Write a class
Vehiclewithbrandand a methodhonk(), and a subclassCarwith adoorsfield. - Give
Vehiclea constructor with the brand and call it fromCar's constructor withsuper. - Override
toStringin both classes so thatCaradds the number of doors to the vehicle's text.