Can we declare more than one class in a single Java program?

JavaObject Oriented ProgrammingProgramming

A single Java program contains two or more classes, it is possible in two ways in Java.

Two Ways of Implementing Multiple Classes in a single Java Program

  • Nested Classes
  • Multiple non-nested classes

How the compiler behave with Multiple non-nested classes

In the below example, the java program contains two classes, one class name is Computer and another is Laptop. Both classes have their own constructors and a method. In the main method, we can create an object of two classes and call their methods.

Example

Live Demo

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.");
   }
}

When we compile the above program, two .class files will be created which are Computer.class and Laptop.class. This has the advantage that we can reuse our .class file somewhere in other projects without compiling the code again. In short, the number of .class files created will be equal to the number of classes in the code. We can create as many classes as we want but writing many classes in a single file is not recommended as it makes code difficult to read rather we can create a single file for every class.

Output

Constructor of Computer class.
Constructor of Laptop class.
Power gone! Shut down your PC soon...
99% Battery available.

How the compiler behave with Nested classes

Once the main class is compiled which has several inner classes, the compiler generates separate .class files for each of the inner classes.

Example

Live Demo

// Main class
public class Main {
   class Test1 { // Inner class Test1
   }
   class Test2 { // Inner class Test2
   }
   public static void main(String [] args) {
      new Object() { // Anonymous inner class 1
      };
      new Object() { // Anonymous inner class 2
      };
      System.out.println("Welcome to Tutorials Point");
   }
}

In the above program, we have a Main class that has four inner classes Test1, Test2, Anonymous inner class 1 and Anonymous inner class 2. Once we compile this class, it will generate the following class files.

Main.class

Main$Test1.class

Main$Test2.class

Main$1.class 

Main$2.class

Output

Welcome to Tutorials Point
raja
Published on 12-Jun-2019 08:00:54
Advertisements