Java final abstract class

后端 未结 9 1943
情歌与酒
情歌与酒 2021-02-02 06:26

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 h

相关标签:
9条回答
  • 2021-02-02 07:21

    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() {}
    }
    
    0 讨论(0)
  • 2021-02-02 07:24

    No, abstract classes are meant to be extended. Use private constructor, it is not a workaround - it is the way to do it!

    0 讨论(0)
  • 2021-02-02 07:24

    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.

    0 讨论(0)
提交回复
热议问题