Abstraction in Java with Example

Abstraction is one of the main pillars of OOPS in Java. In simple words, abstraction can be used to hide unwanted data from the users and only important data is visible to the users.

For Example, The outer structure of a bike is visible to people instead of seeing all components within the bike.

Abstraction can be achieved with the help of an interface or with abstract classes in Java. Let us see a code example of abstraction in Java.

abstract class Vehicle {
  abstract void vehicletype();
}
class Car extends Vehicle {
	  void vehicletype() {
	    System.out.println( "This is a Car." ) ;
	  }
}
class Bike extends Vehicle {
	void vehicletype() {
		System.out.println( "This is a Bike." ) ;
	}
}
class Scooty extends Vehicle {
	void vehicletype() {
		System.out.println( "This is a Scooty." ) ;
	}
}
public class abstractionexample {
	public static void main(String[] args) {
		// Creating objects of all the vehicles
		Car vec1 = new Car();
		Bike vec2 = new Bike();
		Scooty vec3 = new Scooty();
		vec1.vehicletype();
		vec2.vehicletype();
		vec3.vehicletype();
	}
}

Output:

This is a Car.
This is a Bike.
This is a Scooty.

In the above code, we can see that an abstract class Vehicle is created and an abstract method vehicletype is declared inside it. Now since the method is abstract we cannot write any code in the method.

Similarly, another class Car is created which is extending the Vehicle class so it needs to contain the implementation of vehicletype method. Inside the vehicletype method, we are simply printing “This is a Car”.

Bike and Scooty classes are also implemented in a similar way to the Car class.

In the main function objects of all the Car, Bike, and Scooty classes are created and then vehicletype function is called by all of them separately.

I hope by now you must have understood the meaning of abstraction along with its working. Please comment below if you are still facing any doubts and I’ll be happy to resolve them.

Leave a Comment

Your email address will not be published. Required fields are marked *