Why have public static class inside a class

java, nested-class

Solution

I was wondering since even the inner class is public why have it as nested and not a separate class?

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:

Foo foo = new Foo.Builder().setBar(10).build();

Here it makes sense to me to have `Foo.Builder` nested within `Foo` rather than as a peer class which would presumably be called `FooBuilder`.

Note that it also gives some visibility differences compared with just unrelated classes.

Also, can I do this here: `new A.B(SomeObject)` ?

No, because `B` doesn't have a constructor with a `SomeObject` parameter - only `A` does (in the example you've given).

I feel this defeats the purpose of a static class

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.

Problem

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.

Original source

Related problems