Abstract class in Java

Abstract class is such a class where

  • It is not possible to instantiate object from it
  • It is meant for deriving other classes from it
  • It is used as a type
  • It is declared with abstract keyword

An abstract class typically contains one or more abstract methods. Although it is not mandatory to have abstract methods at all. An abstract method is such a method which have method signature but no implementation.

In this context, I like to mention about concrete class which is kind of opposite of abstract class. A concrete class is a class which is not declared with abstract keyword and does not have any abstract methods, i.e. all the methods have implementations. In general, when we call a class, we mean concrete class.

Declaring an abstract class

Consider we are defining a class Vehicle. You know different types of vehicle have different number of wheels. So we can make the method for getting wheel count as abstract.

abstract class Vehicle {
    abstract int getWheelCount();
}

Deriving an abstract class

Now we can derive the Vehicle class into following two concrete classes:

class MotorCycle extends Vehicle {
    @Override
    int getWheelCount() {
        return 2;
    }
}

class Car extends Vehicle {
    @Override
    int getWheelCount() {
        return 4;
    }
}

Use abstract class as Type

You can now use the abstract class as common type for all the concrete classes derived from it. We can call the all the methods including abstract methods through this type. When we call the abstract method, the implementation of the appropriate concrete class will be called.

public class AbstractSample {
    public static void main(String [] argv){
        Vehicle vehicle = new MotorCycle();
        System.out.println("This vehicle has " + vehicle.getWheelCount() + " wheels");
        
        vehicle = new Car();
        System.out.println("This vehicle has " + vehicle.getWheelCount() + " wheels");
    }
}

Output:

This vehicle has 2 wheels
This vehicle has 4 wheels

Some important notes about abstract class

  • Like a normal (concrete) class, abstract class can have constructors. But those can only be called from constructor of derived class by calling super() method.
  • Abstract class can have data members, getter and setter methods.
  • Abstract class can be derived from other abstract or concrete class.
  • Abstract class can implements interface.
Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus