# Abstract classes

In 
Published 2022-12-23

In Java, abstraction is done by abstract classes and interfaces. In this tutorial we are presenting the abstract classes.

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

An abstract method is a method which has only the signature. The method is not defined completely, has no body. This method has the abstract keyword before the signature.

An abstract class is a class which has one or more abstract method.

An abstract class:

  • 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 another class.

Supposing we need to create a VolvoCar class, a CitroenCar class, etc. All the car classes use the same method for starting the car, but the buildCar() method is implemented differently for each car type. We never instantiate Car class.

When we define a VolvoCar and CitroenCar classes we can use a code similar to the following code:

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

If we want to test our code, we need to create our main class:

MainApp.java
public class MainApp {

    public static void main(String [] args) {
        CitroenCar citroenCar = new CitroenCar();
        VolvoCar volvoCar = new VolvoCar();
        citroenCar.buildCar();
        citroenCar.startCar();
        volvoCar.startCar();
    }
}

Once we have all .java files created (in the same folder in my case) we can run javac MainApp.java in order to compile the code.

Now we can run java MainApp command in order to start the application.