Java final abstract class

2019-03-11 00:08发布

I have a quite simple question:

I want to have a Java Class, which provides one public static method, which does something. This is just for encapsulating purposes (to have everything important within one separate class)...

This class should neither be instantiated, nor being extended. That made me write:

final abstract class MyClass {
   static void myMethod() {
      ...
   }
   ... // More private methods and fields...
}

(though I knew, it is forbidden).

I also know, that I can make this class solely final and override the standard constructor while making it private.

But this seems to me more like a "Workaround" and SHOULD more likely be done by final abstract class...

And I hate workarounds. So just for my own interest: Is there another, better way?

9条回答
Melony?
2楼-- · 2019-03-11 00:25

Check this Reference Site..

Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.

Thanks..

查看更多
叛逆
3楼-- · 2019-03-11 00:27

Declare the constructor of the class to be private. That ensure noninstantiability and prevents subclassing.

查看更多
闹够了就滚
4楼-- · 2019-03-11 00:30

Reference: Effective Java 2nd Edition Item 4 "Enforce noninstantiability with a private constructor"

public final class MyClass { //final not required but clearly states intention
    //private default constructor ==> can't be instantiated
    //side effect: class is final because it can't be subclassed:
    //super() can't be called from subclasses
    private MyClass() {
        throw new AssertionError()
    }

    //...
    public static void doSomething() {}
}
查看更多
聊天终结者
5楼-- · 2019-03-11 00:30

No, what you should do is create a private empty constructor that throws an exception in it's body. Java is an Object-Oriented language and a class that is never to be instantiated is itself a work-around! :)

final class MyLib{
    private MyLib(){
        throw new IllegalStateException( "Do not instantiate this class." );
    }

    // static methods go here

}
查看更多
姐就是有狂的资本
6楼-- · 2019-03-11 00:30

This is very simple explanation in plain English.An abstract class cannot be instantiated and can only be extended.A final class cannot be extended.Now if you create an abstract class as a final class, how do you think you're gonna ever use that class, and what is,in reality, the rationale to put yourself in such a trap in the first place?

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-03-11 00:37

You can't mark a class as both abstract and final. They have nearly opposite meanings. An abstract class must be subclassed, whereas a final class must not be subclassed. If you see this combination of abstract and final modifiers, used for a class or method declaration, the code will not compile.

查看更多
登录 后发表回答