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?
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.
abstract methods have the same visibility rules as normal methods, except that they cannot be 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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With