road2victory road2victory - 4 years ago 100
Java Question

Different ways in which we can create a class, which can not be sub classed (Extended)?

Of course by making class as a final we can not able to extend it. Apart from these, are there any other ways in which we can create a class which is not extendable?

Answer Source

Make all the constructors in the class private (or give them default access, if you are only concerned with subclasses in another package), including a private no-argument constructor. Any classes which attempt to inherit from such a class will not compile, even if there is no attempt to create objects of the subclass. You can still provide the ability to instantiate such a class with a static getInstance(arguments)-type method.

The clearest and cleanest way to prevent a class from being extended, however, is to declare the class as final.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download