Abstraction is the process of hiding implementation details and showing the user only the functionality. In other words, only important things are shown to the user, and internal details remain hidden.
Abstraction allows us to focus on what the object is doing rather than how it is doing.
In Java, we have abstract classes and abstract methods. To learn how an abstract class differs from an interface, read the following tutorial: “Difference Between Interface and Abstract class in Java“.
What is an abstract class in Java?
An abstract class is a class that is defined with the keyword abstract and serves only to be inherited. It cannot be instantiated with the keyword new.
An abstract class can have one or more declared methods but not defined.
Declaring an abstract class:
abstract class Vehicle {}
What is an abstract method in Java?
Methods that are declared but not defined are called abstract methods. These methods have no body and are declared with the keyword abstract.
Declaring an abstract method:
public abstract methodA();
Examples and Notes to Remember
The class must also be defined with the abstract keyword if we have at least one abstract method.
If we try to instantiate an abstract class, we get a compile error:
abstract class Vehicle { // ... } class Test { public static void main(String[] args) { Vehicle vehicle = new Vehicle(); // DOES NOT COMPILE } }
If a class inherits an abstract class, it must override all its abstract methods.
abstract class Vehicle { abstract void move(); } class Car extends Vehicle { @Override public void move() { System.out.println("The car is moving..."); } } class Test { public static void main(String[] args) { Vehicle car = new Car(); car.move(); } }
abstract class Vehicle { abstract void move(); } abstract class Car extends Vehicle { }
A non-abstract class that inherits an abstract class that inherits another abstract class must inherit all abstract methods from both parent classes.
abstract class Vehicle { abstract void move(); } abstract class Car extends Vehicle { abstract void startEngine(); } class BlueCar extends Car { @Override void move() { // ... } @Override void startEngine() { // ... } }
An abstract class can have abstract and non-abstract methods. It can also declare constructors, static and final methods.
An example of a class that has abstract and non-abstract methods and its inheritance:
abstract class Vehicle { Vehicle() { // An abstract class can have a constructor defined System.out.println("The constructor of a Vehicle class"); } abstract void move(); // abstract method void print() { // non-abstract method System.out.println("Printing Vehicle..."); } } class Car extends Vehicle { @Override void move() { System.out.println("The car is moving..."); } } class Test { public static void main(String[] args) { Vehicle car = new Car(); car.move(); car.print(); } }