Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a Java class be both abstract and final

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?

like image 435
PC. Avatar asked Oct 01 '13 07:10

PC.


People also ask

Can a class be both final and abstract in Java?

If a class is final you can't extend it further. So, you cannot declare a class both final and abstract.

Can a class be 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.

Can a method be final and abstract at the same time?

No, you cannot make an abstract class or method final in Java because the abstract and final are mutually exclusive concepts.

Can an abstract class be final Why?

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.


2 Answers

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.

like image 195
Joe Lee-Moyet Avatar answered Oct 21 '22 19:10

Joe Lee-Moyet


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() {
}
like image 27
ssantos Avatar answered Oct 21 '22 18:10

ssantos