Monday, May 20, 2024
HomeProgrammingCan we have more than two public Java classes in one file

Can we have more than two public Java classes in one file

Can we have more than two public Java classes in one file:

This is a common Java interview question. The short answer is No. We cannot define more than one public class in the same file. To understand this, let’s take an example.

Learn with an example:

public class Main {
    public static void main(String[] args) {

    }
}

public class SecondClass {
    public static void main(String[] args) {

    }
}

In this example we created one file Main.java and made two public classes in it. A compile error will occur. If you use IntelliJ-Ideeyou will see an error message like below:

An error is displayed that the class is public and we need to create a new file for that class.

If you click on the More actions button, two options will be displayed:

  • You can create another file for the second public class or
  • You can change this non-publicly.

So we can create a new file or change the class to non-public.

Example 1: Change the class to private:

We can change the second class to a non-public class and the program will work:

public class Main {
    public static void main(String[] args) {

    }
}

class SecondClass {
    public static void main(String[] args) {

    }
}

Please note that the name of the file must be the same as that of the public class. In the example above, the file name should be Main.java as is the name of the public class Mainly.

Example 2: Use the class as a nested class:

Another way is to use the class as a nested class. We can create a class within another class. These are called inner and outer class.

public class Main {
    public static void main(String[] args) {

    }

    class SecondClass {
        public void main(String[] args) {

        }
    }
}

Here, Mainly is the outer class and Second class is the inner class. These are called nested classes. For example,

public class Main {
    public static void main(String[] args) {

    }

    class SecondClass {

    }

    class ThirdClass {

    }

    class FourthClass {

    }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments

бнанс Створити акаунт on The Interview Process in Clark, Pampanga
Binance注册奖金 on Venus in Scorpio