You are here

Using multiple classes in a Java program

A Java program can contain any number of classes. Following Java program comprises of two classes: Computer and Laptop. Both 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

  1. class Computer {
  2.   Computer() {
  3.     System.out.println("Constructor of Computer class.");
  4.   }
  6.   void computer_method() {
  7.     System.out.println("Power gone! Shut down your PC soon...");
  8.   }
  10.   public static void main(String[] args) {
  11.     Computer my = new Computer();
  12.     Laptop your = new Laptop();
  14.     my.computer_method();
  15.     your.laptop_method();
  16.   }
  17. }
  19. class Laptop {
  20.   Laptop() {
  21.     System.out.println("Constructor of Laptop class.");
  22.   }
  24.   void laptop_method() {
  25.     System.out.println("99% Battery available.");
  26.   }
  27. }

Output of program:
Multiple classes Java program

You can also create objects in a method of Laptop class. When you compile above code two .class files will be created which are Computer.class and Laptop.class, this has the advantage that you can reuse your .class file somewhere in other projects without compiling the code again. In a nutshell number of .class files created will be 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 unique file for every class. You can also group classes in packages for efficiently managing development of your application.