Sal
Sal

Reputation: 3269

Standard visibility for abstract methods

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

Even though a child class implementing the abstract method will be public, is it still advisable to maintain the abstract method protected?

Upvotes: 7

Views: 12208

Answers (3)

Crazenezz
Crazenezz

Reputation: 3456

Here is the difference for public, protected and private:

Modifier

For method if you set public it can be accessed to all classes within all packages in your project, if you set protected it just can be accessed to all classes within same package or sub class that extend the abstract class.

For question no. 2: Yes, it is.

Upvotes: 3

Jeffrey
Jeffrey

Reputation: 44808

Depends on your use case. If the abstract method only implements some piece of a greater functionality that is available from a public method in your abstract class, then it should probably be protected. If it 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();
}

Upvotes: 11

Luciano
Luciano

Reputation: 8582

I guess it depends on what the method does. If it is something that represents the class (and subclasses) behavior, it should be public. If the method to be implemented by subclasses is internal and used by other methods of the base class (like defining an algorithmic strategy) it should be protected.

Upvotes: 1

Related Questions