Careeroza
Inheritance Basics
IS-A Relationship
Inheritance lets a class (the subclass or child) reuse fields and methods of another class (the superclass or parent) using extends. It models an IS-A relationship: a Car IS-A Vehicle.
Vehicle (brand, start())
/ \
Car Bike (Car adds doors, Bike adds hasGear)- Java supports single inheritance for classes: a class extends only one class.
- Multilevel is fine:
ElectricCar extends Car extends Vehicle. - Private members are not accessible in the child (they still exist inside the object).
- Constructors are not inherited.
First Example
Example
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.brand = "Tata";
car.doors = 4;
car.start(); // inherited from Vehicle
car.openBoot(); // defined in Car
System.out.println(car.brand + " car with " + car.doors + " doors");
}
}
class Vehicle {
String brand;
void start() {
System.out.println(brand + " vehicle starting");
}
}
class Car extends Vehicle {
int doors;
void openBoot() {
System.out.println("Boot opened");
}
}Output
Tata vehicle starting Boot opened Tata car with 4 doors
Types of Inheritance
| Type | Example | Allowed for classes? |
|---|---|---|
| Single | B extends A | yes |
| Multilevel | C extends B, B extends A | yes |
| Hierarchical | B extends A, C extends A | yes |
| Multiple | C extends A, B | no (use interfaces) |
Note: Multiple inheritance of classes is not allowed because of the "diamond problem": if both parents had the same method, Java could not know which one to use.