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 own 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 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 is not 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.