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



Declaring Multiple Classes in Java Program

A single Java program may contain two or more classes, it is possible in two ways:

  • Multiple non-nested classes
  • Nested classes

The Multiple non-nested Classes

We can create as many classes as we want in a single Java program 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.

When we compile a Java program with two or more classes (non-nested), the same number of .class files will be created. This has the advantage that we can reuse our .class file somewhere in other projects without compiling the code again.

Important! only one public class is allowed per Java file, and the name of the file should match the public class name.

Example

In the below example, the Java program contains two classes. 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.

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

On running the above code, you will get the following output:

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

Nested Classes in Java

Another way to declare multiple classes in a single Java program is by using nested classes, where one class is placed within another. On compilation, the compiler generates separate .class files for each of the classes.

Types of nested classes are:

  • Non-static nested class
  • Static nested class
  • Anonymous class
  • Local class

Example

Let's see an example of Java nested classes:

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

In the above program, we have a Main class that has four inner classes. Once we compile this class, it will generate corresponding .class files and display the following output:

Welcome to Tutorials Point
Updated on: 2025-05-20T19:30:19+05:30

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements