Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: how to implement private abstract methods?

Tags:

java

Is it possible to define a private abstract class in Java? How would a Java developer write a construct like below?

public abstract class MyCommand {     public void execute()     {         if (areRequirementsFulfilled())         {             executeInternal();         }     }     private abstract void executeInternal();     private abstract boolean areRequirementsFulfilled(); } 
like image 548
elsni Avatar asked Oct 03 '10 21:10

elsni


People also ask

Can abstract methods be private in Java?

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.

How are abstract methods implemented in Java?

To implement features of an abstract class, we inherit subclasses from it and create objects of the subclass. A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.

Can an interface have private abstract methods?

Rules For using Private Methods in InterfacesPrivate interface method cannot be abstract and no private and abstract modifiers together.


1 Answers

You can't have private abstract methods in Java.

When a method is private, the sub classes can't access it, hence they can't override it.

If you want a similar behavior you'll need protected abstract method.

It is a compile-time error if a method declaration that contains the keyword abstract also contains any one of the keywords private, static, final, native, strictfp, or synchronized.

And

It would be impossible for a subclass to implement a private abstract method, because private methods are not inherited by subclasses; therefore such a method could never be used.


Resources :

  • JLS - 8.4.3. Method Modifiers
  • JLS - 8.4.3.1. abstract Methods
like image 149
Colin Hebert Avatar answered Sep 29 '22 05:09

Colin Hebert