Can we create an object for the abstract class in java?



A method which does not have body is known as abstract method. It contains only method signature with a semi colon and, an abstract keyword before it.

public abstract myMethod();

To use an abstract method, you need to inherit it by extending its class and provide implementation to it.

A class which contains 0 or more abstract methods is known as abstract class. If it contains at least one abstract method, it must be declared abstract.

Instantiating an abstract class

Once a class is abstract it indicates that it may contain incomplete methods hence you cannot create an object of the abstract class.

If you try to instantiate an abstract class a compile time error is generated saying “class_name is abstract; cannot be instantiated”.

Example

In the following Java example, we have an abstract class MyClass which contains an concrete method with name display. We are trying to instantiate this class using the new keyword.

abstract class MyClass {
   public abstract void display() {
      System.out.println("This is a method of abstract class");
   }
   public static void main(String args[]) {
      new MyClass();
   }
}

Compile time error

On compiling this class generates a compile time error as −

MyClass.java:6: error: MyClass is abstract; cannot be instantiated
   new MyClass();
^
1 error

Advertisements