How many class can be public in Java Program?

How many class can be public in Java Program?

How many class can be public in Java Program?


How many class can be public in Java Program?

 

A JAVA Program can have any number no class but at most one class can be declared as public. If there is public class then the name of the Java program must be same as public class otherwise we will get compile time error.

Based on the Java standards and common practices, we should declare every class in its own .java file. And even if we declare multiple classes in a single source file (.java), still each class will have its own .class file after compilation. But the fact is that we can declare more than one class in a single source file with but only one class should be public,

A Java file is called a compilation unit. Each compilation unit may contain any number of top-level classes and interfaces. If there are no public top-level classes then the compilation unit can be named anything. But if there is a class with the public keyword then we have to declare java file name with that class name.

One Java file can consist of multiple classes with the restriction that only one of them can be public.

Conclusion:-

  1. Whenever we compile a java program for every class present in java program .class file will be generated.
  2. We can compile a java program but we have to run a .class file.
  3. Whenever we are executing a java class the corresponding .class will be executed.
  4. If a class doesn’t contain the main method then we will get compile time error –NoSuchMethodFound: Main
  5. If the corresponding .class file not available then we will get runtime exception — NoClassDefFoundError:Test
//How many class can be public in Java Program?
package com.java4us;

public class Test {
    public static void main(String args[]) {
        String s = new String("Java4us");
        Raja r1 = new Raja();
    }
}
class Test1{
    public void hello()
  {
    System.out.println("Hell");
  }
}
  • If there is no public class then we can use any name and there are no restrictions.
  • If Class Test is public then the name of the program should be Test.Java. otherwise, we will get compile time error saying Class Test is public, should be declared in a file named Test.Java.
  • If class Test and Test1 declared as public and name of the program is Test.Java then we will get compile time error saying Class Test1 is public, should be declared in a file named Test.Java 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

%d bloggers like this: