How to call a non-static method of an abstract class from a static method 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.

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.

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

Accessing non-static methods of an abstract class

Since you cannot instantiate an abstract class you cannot access its instance methods too. You can call only static methods of an abstract class (since an instance is not required).

Example

abstract class Example{
   static void sample() {
      System.out.println("static method of the abstract class");
   }
   public void demo() {
      System.out.println("Method of the abstract class");
   }
}
public class NonStaticExample{
   public static void main(String args[]) {
      Example.sample();
   }
}

Output

static method of the abstract class

Example

The only way to access the non-static method of an abstract class is to extend it, implement the abstract methods in it (if any) and then using the subclass object you need to invoke the required methods.

abstract class Example{
   public void demo() {
      System.out.println("Method of the abstract class");
   }
}
public class NonStaticExample extends Example{
   public static void main(String args[]) {
      new NonStaticExample().demo();
   }
}

Output

Method of the abstract class
raja
Published on 05-Aug-2019 17:36:33
Advertisements