Stopping inheritance without using final

前端 未结 8 1578
攒了一身酷
攒了一身酷 2020-12-14 12:51

Is there any other method of stopping inheritance of a class apart from declaring it as final or by declaring its constructor as private?

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 13:32

    • Use final
    • Use private constructors
    • Use a comment:

      // do not inherit
      
    • Use a javadoc comment

    • Make every method final, so people can't override them
    • Use a runtime check in the class constructor:

      if (this.getClass() != MyClass.class) {
          throw new RuntimeException("Subclasses not allowed");
      }
      

提交回复
热议问题