Abstract Class Constructors & Methods in Java


Create a Java program to demonstrate the use of abstract class constructors and methods

  • The Vehicle class is declared as abstract, with an instance variable brand and an abstract method drive().
  • The Car class extends Vehicle and implements the drive() method.
  • The Car class has a constructor that takes a String parameter brand. This constructor calls the superclass constructor using super(brand) to initialize the brand field inherited from Vehicle.
  • In the main method, an instance of Car is created with the brand name "Toyota".
  • When the drive() method is called on the Car object, it prints the message "Driving a Toyota car", using the brand name initialized in the constructor.

Source Code

abstract class Vehicle
{
	String brand;
 
	Vehicle(String brand)
	{
		this.brand = brand;
	}
 
	abstract void drive();
}
 
class Car extends Vehicle
{
	Car(String brand)
	{
		super(brand);
	}
 
	@Override
	void drive()
	{
		System.out.println("Driving a " + brand + " car");
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		Car car = new Car("Toyota");
		car.drive();
	}
}

Output

Driving a Toyota car