Non-extendable Class
First thing comes in mind when somebody say Non-extendable class , that is final class. Marking a class as “final” , no one can extends the particular class.
But there is another tricky way to restricting any other class from extending your class.
Thinking how ….?
Simple, marking all available constructors of a class as private. As per constructor chaining principle in class hierarchy , every child class constructor should delegate call to super class explicitly or implicitly. In implicit case, call get delegate to class’s default constructor.
If all available constructors of the class are private then no other class can not extend it.
1: public class MyClass {2:3: private MyClass(){4: System.out.println("Inside Singleton Constructor");5: }6:7: }8:9: class MyChildClass extends MyClass{ // compilation error10:11: }
Cool!
ReplyDelete