A Java class can inherit attributes and methods from another Java class. Below are some important points about Java inheritance:

  • The class that inherits another class is called subclass
  • The class that another class inherits from is called superclass
  • A class can inherit from only one superclass
  • A superclass can be inherited from multiple subclasses

Notes: A Java class can extends (inherits) from only one superclass and can implements multiple interfaces.

In the example below, the Car and Bike classes both extends the Vehicle class:

class Vehicle {
	String color;
	int noOfWheels;

	public Vehicle(String color, int noOfWheels) {
		super();
		this.color = color;
		this.noOfWheels = noOfWheels;
	}

	public void drive() {
		System.out.println("Drives on " + noOfWheels + " wheels");
	}

}

class Car extends Vehicle {

	public Car(String color, int noOfWheels) {
		super(color, noOfWheels);
	}

}

class Bike extends Vehicle {

	public Bike(String color, int noOfWheels) {
		super(color, noOfWheels);
	}

}

class Main {
	public static void main(String[] args) {

		Car car = new Car("black", 4);
		System.out.println("I am a " + car.color + " car");
		car.drive();

		Bike bike = new Bike("red", 2);
		System.out.println("I am a " + bike.color + " bike");
		bike.drive();
	}
}