Suppose I've a utility class which contains only static methods and variables. e.g:
public abstract final class StringUtils
{
public static final String NEW_LINE = System.getProperty("line.separator");
public static boolean isNotNullOrSpace(final String string)
{
return !(string == null || string.length() < 1 || string.trim().length() < 1);
}
}
In this scenario, it makes sense to make the class both abstract and final. Abstract because making an object of this class will be of no use as all methods are accessible statically. Final because the derived class cannot inherit anything from this class as it does not have any non-static member.
C# allows static modifier for such classes. Why doesn't Java support this?
If a class is final you can't extend it further. So, you cannot declare a class both final and abstract.
therefore, a final abstract combination is illegal for classes. Hence, a final class cannot contain abstract methods whereas an abstract class can contain a final method.
No, you cannot make an abstract class or method final in Java because the abstract and final are mutually exclusive concepts.
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.
It is not possible because the Java language specification states that:
It is a compile-time error to declare an abstract class type such that it is not possible to create a subclass that implements all of its abstract methods [1]
Other than this, there is no inherent reason why an abstract final class would be illogical - the word abstract is generally used in contrast to concrete to mean that no direct instances of a type may exist.
This is the same reason why abstract methods cannot have access modifier private.
A final
class can't be extended, an abstract
class needs to be extended in order to be instantiated. Therefore, a final abstract
class would be a logical contradiction.
If your class just have static
methods, maybe you should just hide
its constructor, by defining it as private
.-
private StringUtils() {
}
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