Why Java class cannot be abstract and final

Suppose I have a utility class that contains only static methods and variables. eg:

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 abstract and final. Annotation, since creating an object of this class will be useless, since all methods are available statically. Final, because a derived class cannot inherit any of this class, since it does not have any non-static element.

C # enables the static modifier for such classes. Why does Java not support this?

+4
source share
5 answers

final , abstract , . , final abstract .

static, , hide , private.-

private StringUtils() {
}
+9

, Java , :

, , [1]

, , - , , .

, .

+9

final class, abstract class .

+1

, , . - ( ), . , , , , , ( , ) . . ( ), , .

+1
source

what you can do is make your class abstract and make all your methods final. How:

public abstract class MyClass {
    public final static void myMethod1() {
    }

    public final static void myMethod2() {
    }
}

The compiler will check this and throw an error if you try to instantiate the MyClass object, and you also cannot override the final methods if any subclass extends MyClass

0
source

All Articles