Can we declare an abstract method, private, protected, public or default 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.

Declaring an abstract method private

If a method of a class is private, you cannot access it outside the current class, not even from the child classes of it.

But, incase of an abstract method, you cannot use it from the same class, you need to override it from subclass and use.

Therefore, the abstract method cannot be private.

If, you still try to declare an abstract method final a compile time error is generated saying “illegal combination of modifiers − abstract and private”.

Example

In the following Java program, we are trying to declare an abstract method private.

abstract class AbstractClassExample {
   private static abstract void display();
}

Compile time error

On compiling, the above program generates the following error.

AbstractClassExample.java:2: error: illegal combination of modifiers: abstract and private
   private static abstract void display();
                              ^
1 error

Declaring an abstract method protected

Yes, you can declare an abstract method protected. If you do so you can access it from the classes in the same package or from its subclasses.

(Any you must to override an abstract method from the subclass and invoke it.)

Example

In the following Java program, we are trying to declare an abstract method protected.

 Live Demo

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

Output

This is the subclass implementation of the display method
raja
Published on 03-Jul-2019 17:48:44
Advertisements