Abstraction hides certain details of implementation and only displays necessary information to the consumer. Java achieves this by using abstract classes or interfaces.

Java abstract class:

  • The abstract keyword is used to define an abstract class
  • An abstract class cannot be instantiated
  • An abstract class can be inherited from another class ( which can be either abstract or not)
  • An abstract class can have both abstract and regular methods (However, an abstract method cannot be defined in regular class)

Java abstract class example:

package com.devspeedup.javaabstract;

abstract class Vehicle {

	int noOfWheels;
	
	Vehicle(int noOfWheels) {
		this.noOfWheels = noOfWheels;
	}
	
	public abstract void introduce();
	
	public void drive() {
		System.out.println("Drive on " + noOfWheels + " wheels");
	}

}

class Car extends Vehicle {

	Car(int noOfWheels) {
		super(noOfWheels);
	}

	public void introduce() {
		System.out.println("Hello! I am a car");  
	}

}

class Bike extends Vehicle {

	Bike(int noOfWheels) {
		super(noOfWheels);
	}

	public void introduce() {
		System.out.println("Hello! I am a bike");  
	}

}

class Main {
	public static void main (String[] args) {
		
		Car car = new Car(4);
		Bike bike = new Bike(2);
		
		car.introduce();
		car.drive();
		
		bike.introduce();
		bike.drive();
	}
}

The result from running the main method in the Main class: