Loading lessons...
Java Inheritance
Java Inheritance
Inheritance lets one class use the attributes and methods of another class. It helps you reuse code.
Superclass and subclass
- The class that provides the members is the superclass (parent).
- The class that inherits is the subclass (child).
- Use
extendsto inherit.
class Vehicle {
protected String brand = "Ford";
public void honk() {
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang";
public static void main(String[] args) {
Car myCar = new Car();
myCar.honk();
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
The Car object can use the honk() method and the brand attribute from Vehicle.
The protected modifier
protected makes a member visible in the same package and in subclasses, so Car can read brand.
Why use inheritance
- Reuse code from a parent class.
- Build new classes on top of existing ones.
- Keep related classes consistent.
Important rule
Java supports single inheritance for classes: a class can extend only one superclass.
TL;DR
- Use
extendsto inherit from a class. - The subclass gets the superclass methods and attributes.
protectedmembers are visible to subclasses.