简体   繁体   中英

Declaring nested classes in separate files

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?

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.

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.

不,您不能使用javac作为编译器将它们放在单独的源文件中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM