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

时光总嘲笑我的痴心妄想 提交于 2019-11-29 04:51:53

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() {
}
Joe Lee-Moyet

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.

user1515520

There is no reason except subjectivity but you can accomplish the same objective by making your class abstract and make all your methods final. Like:

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

    public final static void myMethod2() {
        …
    }
}

The compiler will check this and give an error if you try to instantiate an object of MyClass, and it will also not be possible to override the final methods when any subclass extends MyClass

In Java an instance of an abstract class cannot be created, we can only have references of abstract class type. So there if we make abstract class final then we wont be able to extend it. abstract and final are the mutual exclusive concept. that's why Java compiler throws a compile time error when you try to make an abstract class final in Java

Due to some certain reasons we can not final use final with abstract class. 1. If we define abstract final then we can't extend it. 2. If we are defining abstract class as final the it will give the compile time error..

A method can never, ever, ever be marked as both abstract and final, or both abstract and private. Think about it—abstract methods must be implemented (which essentially means overridden by a subclass) whereas final and private methods cannot ever be overridden by a subclass. Or to phrase it another way, an abstract designation means the superclass doesn't know anything about how the subclasses should behave in that method, whereas a final designation means the superclass knows everything about how all subclasses (however far down the inheritance tree they may be) should behave in that method. The abstract and final modifiers are virtually opposites. Because private methods cannot even be seen by a subclass (let alone inherited), they too cannot be overridden, so they too cannot be marked abstract.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!