Is this a good way to encapsulate a derived class?

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 do not want these derived classes to be used directly outside the body of the base class.

Is this a good way to do this? I am not sure about this, because these derivatives may consist of 100 lines of code, which will probably make it difficult to understand the base class.

+4
source share
4 answers

Perhaps, but often not.

My main concern is that your design depends on fear (“someone may abuse it”). This can lead to all kinds of problems. There is too much encapsulation, especially when you have complex code that should have "I could use this with a few changes" errors on the consumer side.

, . , ?

static factory. , .

- . , :

/*package*/ class Derived extends Base { ... }

, ( ", public " ).

, .

+10

, Base Derived Derived . .

, , themsevles Derived.

+2

, ?

class Derrived extends Base {
}

public . , protected. Derrived.

+2

, Base, .

My personal preference is that nested classes go to the end of the outer class, that is, they do not clutter the outer class, making it more readable.

+1
source

All Articles