Abstract Class in Java

Niluka Sripali Monnankulama
Many Minds
Published in
2 min readDec 28, 2020

Here I will use a simple way to easily identify what is the abstract class in Java.

Lets start with Simple example, shall we consider a class “Vehicle”. and there is a method “park()”

class Vehicle {  void park(){

//meaning ????
}
}

As I mentioned above, can this park () method be used with a class of Vehicles, or does it have any meaning with that class?
So if it’s Car or Van, we can use the park () method, right?

Similarly, there are certain methods that do not make sense for a specific class (e.g. mother class).In fact we can call the abstract method is like a structure.

We know if there is no body that cannot use “{}” for a method in Java.

So if there is a method without a body we can use below (end with semicolon),

class Vehicle { void park();
}

But is that correct ??? NO

In these scenarios, we use a prefix keyword call “abstract”

If there is an abstract method, we must use the keyword “abstract” for the class, then we call it abstract class.

abstract class Vehicle { abstract void park();
}

Now the question is, can there be general methods in an abstract class? Yes, it can

abstract class Vehicle { abstract void park(); void name(){}
}

The other important thing is that an abstract class cannot create an object. So there is no Constructor for the abstract class.

So can we extends sub class,

if there is a sub class Car ,

class Car extends Vehicle {}

And they can refer sub class objects.

Vehicle vehicleObj = new Car();

Next thing is important, consider both classes we used above,

abstract class Vehicle {abstract void park();void name(){}
}
class Car extends Vehicle {
}

In above example, we know that Car class inherits name() method as well as abstract park() method. (OOP concepts).

So according to our abstract logic, then we have to use our Car class as below, because it is containing an abstract method.

So according to our abstract logic, our Car class should be used as follows, because it inherits an abstract method (park()).

abstract class Vehicle {abstract void park();void name(){}
}
abstract class Car extends Vehicle {
}

But we can use these methods in other ways,

  1. we an override the abstract method in the sub class.
  2. add a method body
abstract class Vehicle {abstract void park();void name(){}
}
class Car extends Vehicle { void park(){ //Body
}
}

Simply , if you extend an abstract class, either override abstract methods or make that subclass an abstract class as well.

Thats it 😊.

--

--

Niluka Sripali Monnankulama
Many Minds

An IT professional with over 7+ years of experience. Member of the WSO2 Identity & Access Management Team.