I was going through some code and I saw this:
public class A {
public A(SomeObject obj) {
//Do something
}
//Some stuff
public static class B {
//Some other stuff
}
}
I was wondering since even the inner class is public why have it as nested and not a separate class?
Also, can I do this here: new A.B(SomeObject) ? I feel this defeats the purpose of a static class but I saw this implementation as well so wanted to know.
That’s really a matter to ask whoever wrote the class. It can allow the outer class to act as a “mini-namespace” though – if the nested class is only useful in the context of the outer class, it seems reasonable. It indicates deliberate tight coupling between the two classes. I most often see this in the context of the builder pattern:
Here it makes sense to me to have
Foo.Buildernested withinFoorather than as a peer class which would presumably be calledFooBuilder.Note that it also gives some visibility differences compared with just unrelated classes.
No, because
Bdoesn’t have a constructor with aSomeObjectparameter – onlyAdoes (in the example you’ve given).You should try to work out exactly what you deem the purpose of a static class to be, and in what way this defeats that purpose. Currently that’s too vague a statement to be realistically discussed.