I have an abstract class for which I want to allow only single level of inheritance.
Here I do not want any other class to extend SpecialX. Can I do anything to BaseX to enforce this single level inheritance? I do not have any control over SpecialX so putting restriction on this wont be a solution.
There's a way to do something kind of similar, that may be what you want: you can prevent anyone from ever extending your classes, except the classes that you have defined in the same file - by using nested classes. Here's how:
The private constructor in BaseX prevents other classes from successfully extending the class (or at least, from extending and instantiating it). Except for other classes declared within the same top-level class.
Now, is this actually useful for anything? Dunno. Why do you want to place this limitation on a class, anyway?
Prasad prap wrote:what do you mean by "not working in all scenarios"? Can you clarify a bit?
Basically, Darryl's solution doesn't prevent someone from creating a subclass more than one level from your base class. What is does do is prevent someone from actually instantiating that class at runtime.
Will this work?
PS... although a terrible design, it is an interesting solution. Darryl, you get a cow...