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

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.


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


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.


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.







Welcome to Tutorials Point