Stopping inheritance without using final

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

提交回复
热议问题