java在同一个源文件中定义多个类

如果出于封装目的需要,可以在同一个源文件中定义多个类,如下例所示:

public class MultipleClassesInSameFile {
    public static void main(String[] args) {
 
        System.out.println(GenerateMessage.generateMessage());
        System.out.println(AnotherMessage.generateAnotherMessage());
    }
}
 
class GenerateMessage {
    static String generateMessage() {
        return "Here is one message";
    }
}
 
class AnotherMessage {
    static String generateAnotherMessage() {
        return "Here is another message";
    }
}

执行时:

$ java MultipleClassesInSameFile.java

将输出:

Here is one message
Here is another message
java在同一个源文件中定义多个类

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注