我们可以在一个 Java 程序中声明多个类吗?\
javaobject oriented programmingprogramming更新于 2024/5/12 0:30:00
一个 Java 程序包含两个或更多类,在 Java 中有两种方法可以实现。
在一个 Java 程序中实现多个类的两种方法
- 嵌套类
- 多个非嵌套类
编译器如何处理多个非嵌套类
在下面的示例中,Java 程序包含两个类,一个类名为 Computer,另一个类名为 Laptop。这两个类都有自己的构造函数和一个方法。在 main 方法中,我们可以创建两个类的对象并调用它们的方法。
示例
public class Computer { Computer() { System.out.println("Constructor of Computer class."); } void computer_method() { System.out.println("Power gone! Shut down your PC soon..."); } public static void main(String[] args) { Computer c = new Computer(); Laptop l = new Laptop(); c.computer_method(); l.laptop_method(); } } class Laptop { Laptop() { System.out.println("Constructor of Laptop class."); } void laptop_method() { System.out.println("99% Battery available."); } }
当我们编译上述程序时,将创建两个 .class 文件,即 Computer.class 和 Laptop.class。这样做的好处是,我们可以在其他项目中重用我们的 .class 文件,而无需再次编译代码。简而言之,创建的 .class 文件的数量将等于代码中的类数量。我们可以创建任意数量的类,但不建议在单个文件中编写多个类,因为这会使代码难以阅读,相反,我们可以为每个类创建一个文件。
输出
Constructor of Computer class. Constructor of Laptop class. Power gone! Shut down your PC soon... 99% Battery available.
编译器如何处理嵌套类
一旦编译了具有多个内部类的主类,编译器就会为每个内部类生成单独的 .class 文件。
示例
// 主类 public class Main { class Test1 { // 内部类 Test1 } class Test2 { // 内部类 Test2 } public static void main(String [] args) { new Object() { // 匿名内部类 1 }; new Object() { // 匿名内部类 2 }; System.out.println("Welcome to Tutorials Point"); } }
在上面的程序中,我们有一个 Main 类,它有四个内部类 Test1、Test2、匿名内部类 1 和 匿名内部类 2。一旦我们编译这个类,它将生成以下类文件。
Main.class
Main$Test1.class
Main$Test2.class
Main$1.class
Main$2.class
输出
Welcome to Tutorials Point