21xrx.com
2024-03-29 13:41:38 Friday
登录
文章检索 我的文章 写文章
在 Java 程序中使用多个类
2021-07-08 16:41:08 深夜i     --     --
a v a 使

Java 程序可以包含任意数量的类。 下面的程序包含两个类:Computer 和 Laptop,这两个类都有它们的构造函数和一个方法。 在 main 方法中,我们创建两个类的对象并调用它们的方法。

 

在Java程序中使用两个类

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 my = new Computer();
    Laptop your = new Laptop();
   
    my.computer_method();
    your.laptop_method();
  }
}


class Laptop {
  Laptop() {
    System.out.println("Constructor of Laptop class.");
  }
 
  void laptop_method() {
    System.out.println("99% Battery available.");
  }
}

 

程序输出:

您还可以在 Laptop 类的方法中创建对象。 编译上述程序时,会创建两个 .class 文件,分别是 Computer.class 和 Laptop.class。 它的优点是您可以在其他项目中的某处重用您的 .class 文件,而无需重新编译代码。 简而言之,创建的 .class 文件数等于程序中的类数。 您可以根据需要创建任意数量的类,但不建议在单个文件中编写多个类,因为这会使代码难以阅读。 相反,您可以为每个类创建一个单独的文件。 您还可以在包中对类进行分组,以有效管理应用程序的开发。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复