Standard Visibility for Abstract Methods

This may seem like a silly question, but I would like to know the "best practices" when creating abstract methods. Should their visibility be open or protected?

Although the child class that implements the abstract method will be publicly available, is it still advisable to support a protected abstract method?

+7
source share
3 answers

Depends on your use case. If an abstract method implements only part of the greater functionality available from the public method in your abstract class, then it should probably be protected. If this is a standalone method that can / should be called from another class, make it public.

Examples:

public abstract class Foo implements Closeable { public final void close() { // do whatever doClose(); } protected abstract void doClose(); } public abstract class Bar { public void read(byte[] b) { for(int x = 0; x < b.length; x++) { b[x] = read(); } } public abstract int read(); } 
+10
source

Here is the difference for public, secure, and private:

Modifier

For a method, if you set up public access, it can be accessed by all classes in all packages of your project, if you set protection, it can only be accessed by all classes within the same package or subclass that extend the abstract class.

On the issue no. 2: Yes, it is.

+2
source

I think it depends on what this method does. If this is what the behavior of the class (and subclasses) represents, it should be publicly available. If the method implemented by the subclasses is internal and is used by other methods of the base class (for example, defining an algorithmic strategy), it must be protected.

+1
source

All Articles