1
public class A
{
}  

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

Why cant we declare both class as public?
Why only Main class can be public? i know that by making class public ,it will allow you access in package ok ,but what if i make

     public    class a
     { 

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

     }
  }

why this code give error do we really need to notify that main class is public bcoz every class is public

user2461247
  • 479
  • 1
  • 5
  • 14

2 Answers2

4

Because one .java file can contain only one public class.

If you want these two classes to be public they have to be put into two .java files: A.java and B.java.

From the JLS 7.6. Top Level Type Declarations:

This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a Java compiler to find a named class within a package. In practice, many programmers choose to put each class or interface type in its own compilation unit, whether or not it is public or is referred to by code in other compilation units.

Adam Siemion
  • 15,569
  • 7
  • 58
  • 92
2

The filename for a Java class is the public class' name. You cannot have 2 file names, hence you cannot have 2 public classes.

Vaishak Suresh
  • 5,735
  • 10
  • 41
  • 66