Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard visibility for abstract methods

Tags:

java

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?

like image 240
Sal Avatar asked Apr 12 '12 00:04

Sal


People also ask

What should be the visibility of abstract methods in abstract class?

Abstract methods are declaration only and it will not have implementation. It will not have a method body. A Java class containing an abstract class must be declared as abstract class. An abstract method can only set a visibility modifier, one of public or protected.

Should abstract methods be public?

abstract methods have the same visibility rules as normal methods, except that they cannot be private .

Can I assign an abstract method Private visibility?

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.

Can abstract class have private concrete methods?

In Java, it is not possible to instantiate an abstract class. An abstract class may contain abstract and concrete methods (i.e with body implementation). Yes, subclasses inherit/override concrete methods from an abstract superclass if they are not private, final or static, they can be overridden.


1 Answers

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();
}
like image 150
Jeffrey Avatar answered Oct 15 '22 13:10

Jeffrey