I have the following class:
public class Base{
private static class Derived extends Base{ }
private static class SuperDerived extends Base{ }
public static Base createDerived(){ return new Derived(); }
public static Base createSuperDerived(){ return new SuperDerived(); }
}
I don't want those derived classes be used outside of the Base class body directly.
Is that a good way to do that? I'm not sure about that thing because those derived may consist of 100 lines of code that will probably make the Base class hard to understand.
Maybe but often not.
My main concern is that your design is driven by fear ("someone might abuse"). This can lead to all kinds of problems. There is a thing like too much encapsulation, especially when you have complex code which is bound to have "I could use that with a small change" bugs on the consumer side.
Often, it's enough to label a class as internal and not protect it very much. What's the point of protecting something that no one cares about?
I also advise against using static
factory methods. It will cause all kind of pains when you have to write unit tests.
Your other concern is class size. If you still feel the pressure to protect the code, make the classes package private:
/*package*/ class Derived extends Base { ... }
The comment has no effect but documenting the intention (so no one thinks "oh, there is a public
missing").
That way, only classes in the same package can access them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With