Stopping inheritance without using final

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

    Make your constructors private and provide factory functions to create instances.

    This can be especially helpful when you want to choose an appropriate implementation from multiple, but don't want to allow arbitrary subclassing as in

    abstract class Matrix {
       public static Matrix fromDoubleArray(double[][] elemens) {
         if (isSparse(elements)) {
          return new SparseMatrix(elements);
        } else {
          return new DenseMatrix(elements);
        }
      }
      private Matrix() { ... }  // Even though it's private, inner sub-classes can still use it
      private static class SparseMatrix extends Matrix { ... }
    }
    
    0 讨论(0)
  • 2020-12-14 13:55

    Two more options:

    • make each method final, so people can't override them. You avoid accidental calling of methods from subclass this way. This doesn't stop subclassing though.

    • put check into constructor for class:

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

      Then nobody will be able to instantiate subclass of your class.

    (Not that I suggest using these techniques, it just came to my mind. I would use final class and/or private constructor)

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