You are here

Using multiple classes in a Java program

A Java program may contain any number of classes. The following program comprises of two classes: Computer and Laptop, both the classes have their constructors and a method. In the main method, we create objects of two classes and call their methods.

Using two classes in Java program

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();

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

Output of program:
Multiple classes Java program

You can also create objects in a method of Laptop class. When you compile the above program, two .class files are created, which are Computer.class and Laptop.class. Its advantage is you can reuse your .class file somewhere in other projects without recompiling the code. In a nutshell number of .class files created are equal to the number of classes in the program. You can create as many classes as you want, but writing many classes in a single file isn't recommended, as it makes code difficult to read. Instead, you can create a separate file for every class. You can also group classes in packages for efficiently managing the development of your application.