How to implement abstraction in Java

Data abstraction is a method where essential elements are displayed to the user and trivial elements are kept hidden.

In Java, abstraction is achieved by using the abstract keyword for classes and interfaces. In abstract classes, we can have abstract methods as well as concrete methods.

svg viewer

Code

The following piece of code shows abstraction in Java:

// Abstraction in Java
abstract class ElectricityBill
{
//abstract method
abstract float computeBill();
}
class Commercial extends ElectricityBill
{
@Override
float computeBill() {
return 1.25*100;
}
}
class Domestic extends ElectricityBill
{
@Override
float computeBill() {
return 0.25*75;
}
}
Copyright ©2024 Educative, Inc. All rights reserved