2

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?

Community
  • 1
  • 1
Saturn
  • 17,888
  • 49
  • 145
  • 271
  • 4
    I mean ... word "Nested" kinda answers this. – Brian Roach Jan 05 '14 at 02:37
  • 1
    @BrianRoach: I don't see a reason why would that mean I can't declare a nested class in another file. I mean, it's just another file. The compiler could say *"welp, I'm gonna grab the class in that file and pretend it is nested inside this other one"*. Simply to make the project look more organized. Like C++, or Ruby, dunno. – Saturn Jan 05 '14 at 03:05

3 Answers3

2

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.

CodeMonkey
  • 629
  • 7
  • 16
1

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.

nbanic
  • 1,270
  • 1
  • 8
  • 11
doomsdaymachine
  • 647
  • 6
  • 11
0

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

bmargulies
  • 97,814
  • 39
  • 186
  • 310