Stopping inheritance without using final

前端 未结 8 1522
攒了一身酷
攒了一身酷 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:30

    Final was created to solve this problem.

    0 讨论(0)
  • 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");
      }
      
    0 讨论(0)
  • 2020-12-14 13:41

    Using final is the canonical way.

    public final class FinalClass {
      // Class definition
    }
    

    If you want to prevent individual methods from being overridden, you can declare them as final instead. (I'm just guessing here, as to why you would want to avoid making the whole class final.)

    0 讨论(0)
  • 2020-12-14 13:44

    Without using a final class, you can basically make all the constructors private:

    public class A {
        private A() {} //Overriding default constructor of Java
    }
    

    Which although will also make this class abstract-ish by disallowing creating an object of this class, yet as any inheritance requires super(); in the constructor, and because the constructor is private, a compilation error will be the maximum you can get when one tries to inherit that class. Yet, I would recommend using final instead as it is less code and includes the option of creating objects.

    0 讨论(0)
  • 2020-12-14 13:47

    I'd have to say it's typically bad form. Though there are almost always cases where something is valid, I'd have to saying stopping inheritance in an OO world is normally not a good idea. Read up on the Open-Closed Principle and here. Protect your functionality but don't make it impossible for the guy who comes in and supports it...

    0 讨论(0)
  • 2020-12-14 13:50

    A comment

    //Do not inherit please
    
    0 讨论(0)
提交回复
热议问题