Module 3: Object-Oriented Programming
Inheritance
Reuse and specialize behaviour using inheritance.
Inheritance allows one class to derive from another. The subclass inherits accessible members from its superclass and can add or specialize behaviour. Java classes use single class inheritance: a class can extend one direct superclass.
Basic example#
class Animal {
void eat() {
System.out.println("Eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking");
}
}
class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();
}
}
Dog extends Animal, so a Dog instance can use the accessible eat() method as well as its own bark() method.
Override inherited behaviour#
A subclass can override an inherited instance method to provide a specialized implementation:
class Animal {
void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Woof");
}
}
@Override tells the compiler that the method is intended to override an inherited method; it helps catch spelling and signature mistakes.
The super keyword#
super can refer to superclass members and invoke a superclass constructor. A constructor call such as super(name) must appear first in a constructor when used explicitly.
When to use inheritance#
Use inheritance when the relationship genuinely represents an “is-a” relationship and the subclass can be used where the superclass is expected. Do not use it only to share a few lines of code. Composition—having one object use another—can be a more flexible design.
Practice#
Create a Vehicle superclass and a Car subclass. Add one method to each class and call both methods on a Car object.