简体   繁体   English

在单独的文件中声明嵌套类

[英]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. 这个问题: 将嵌套类放在单独的文件中告诉我使用恰好在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. 您无法在Java中执行此操作。

As a note, if you were using a language that supports partial classes (such as C#) you could do 注意,如果您使用支持部分类的语言(例如C#),则可以执行

File 1: 文件1:

partial class OuterClass {
}

File 2: 档案2:

partial class OuterClass {
    class StaticNestedClass {

    }
}

but Java doesn't have partial classes so this wouldn't be of help for this particular situation. 但是Java没有局部类,因此对于这种特殊情况不会有帮助。 In Java a class can only be declared in one file. 在Java中,一个类只能在一个文件中声明。

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作为编译器将它们放在单独的源文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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