Question

Here we have a nested class:

class OuterClass {
    ...
    static class StaticNestedClass {
        ...
    }

}

Instead of writing them in the same file, can I declare them in separate files?

This question: Putting Nested Classes In Separate Files tells me to use a refactor option that happens to be available in Eclipse. I use it, but I end up with two files:

class OuterClass {
    ...
}

and

class StaticNestedClass {

}

But as far as I'm concerned, that's no longer a nested class, right?

Was it helpful?

Solution

You cannot do this in Java.

As a note, if you were using a language that supports partial classes (such as C#) you could do

File 1:

partial class OuterClass {
}

File 2:

partial class OuterClass {
    class StaticNestedClass {

    }
}

but Java doesn't have partial classes so this wouldn't be of help for this particular situation. In Java a class can only be declared in one file.

OTHER TIPS

Nested class is a class that's literally INSIDE another class. No, it's not possible to have a nested class in a separate file because then it would no longer be a nested class, it would be just another class.

No you cannot have them in separate source files using javac as a compiler.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top