gpt4 book ai didi

java - 是否有必要将此 java 程序分为两类?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:09:48 25 4
gpt4 key购买 nike

像下面这样将所有类代码保存为单独的 .java 文件很重要吗?

Outer.java,
Inner.java,
Test.java

或者我可以制作一个 java 文件作为 Test.java。请解释匿名类,我们如何在java中创建匿名类,以及与普通类相比有什么优势/劣势?

class Outer {
private int data = 50;

class Inner {
void msg() {
System.out.println("Data is: " + data);
}
}
}

class Test {
public static void main(String args[]) {
Outer obj = new Outer();
Outer.Inner in = obj.new Inner();
in.msg();
}
}

最佳答案

参见 Code Conventions for the Java programming language :

Each Java source file contains a single public class or interface. When private classes and interfaces are associated with a public class, you can put them in the same source file as the public class. The public class should be the first class or interface in the file.

我认为这应该可以回答您的问题。正如我在评论中所述,不建议编写包含多个不相关 类的文件。但是,如果文件中的那个公共(public)类有相关联的类,则可以将它们放在同一个源文件中。

关于java - 是否有必要将此 java 程序分为两类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21398325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com