Can we define an abstract class without abstract method in java?

Java 8Object Oriented ProgrammingProgramming

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.

Abstract class

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.

And yes, you can declare abstract class without defining an abstract method in it. Once you declare a class abstract it indicates that the class is incomplete and, you cannot instantiate it.

Hence, if you want to prevent instantiation of a class directly you can declare it abstract.

If you want to use the concrete method in an abstract class you need to inherit the class, provide implementation to the abstract methods (if any) and then, you using the subclass object you can invoke the required methods.

Example

In the following Java example, the abstract class MyClass contains a concrete method with name display.

From another class (AbstractClassExample) we are inheriting the class MyClass and invoking the its concrete method display using the subclass object.

 Live Demo

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

Output

This is a method of abstract class
raja
Published on 03-Jul-2019 17:34:14
Advertisements