Raushan Kumar’s Post

In Java, a class is not final, but we need to restrict the creation of a child class. How is it possible? By declaring each constructor as private, we can stop the child classes. eg: # parent class class P{ private P(){} } # child class class C extends P{ public C(){ super(); // ---> tries to call parent's constructor } } super() will attempt to call the parent no-arg constructor, but since it is private, the compiler throws an error. So even though the class is not final, inheritance becomes impossible. Would love to know if there are other ways to restrict child class creation! #java #oops #constructer

To view or add a comment, sign in

Explore content categories