Can an object of an abstract class be created in Java?

Modified on Tue, 28 Mar, 2023 at 4:07 PM

Description: An abstract class is a class that cannot be instantiated directly. It is used as a base class for other classes to inherit from. Attempting to create an object of an abstract class will result in a compile-time error.


Code example:


abstract class Animal {

public abstract void sound();

}


class Dog extends Animal {

public void sound() {

System.out.println("Woof");

}

}


public class Main {

public static void main(String args[]) {

Animal animal = new Animal(); // error: Animal is abstract; cannot be instantiated

}

}


Debugging steps:


  1. Check that the class being instantiated is not an abstract class.

  2. If the class is an abstract class, check that it is being used correctly as a base class for other classes to inherit from.

  3. If an object needs to be created for the abstract class, create a subclass that extends the abstract class and override any abstract methods.


Extra information:


  • Abstract classes are often used to define common functionality for a group of related classes.

  • An abstract class can contain both abstract and non-abstract methods.

  • Abstract classes cannot be marked as final.

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article