# Abstraction in Java

In 
Published 2022-12-23

In Java OPP (Object-Oriented Programming) we speak about 4 main concepts:

Abstraction in general hides the implementation details from the user. We can see WHAT an object can do, but not HOW.

Abstraction in Java is realized by using abstract classes and interfaces.

# Abstract classes

An abstract class is a class which:

  • cannot be instantiated
  • function as a base for other subclasses

Here we have an example of abstract class in Java:

Car.java
public abstract class Car {
 
    public void startCar(){
        System.out.println("Now we start a car");
    };
     
    abstract void buildCar();
}

This class is never instantiated, but can be used to create other classes.

For instance, we can create a VolvoCar class as below:

VolvoCar.java
public class VolvoCar extends Car {
    
    @Override
    void buildCar() {
        System.out.println("Implement buildCar for VolvoCar.");
    }
}

This new class could be instantiated.

You can see a full example of an abstract class usage here.

# Interfaces in Java

An interface class in Java is a class which:

  • define a collection of public and abstract methods (which will be implemented later)
  • could define a collection of public, static & final variables
  • (starting from Java 8) could define a default method and some static methods

You can see a full example of an interface usage here.