How many public classes of the same name it can have in Java?



A Java file contains only one public class with a particular name. If you create another class with same name it will be a duplicate class. Still if you try to create such class then the compiler will generate a compile time error.

Example

 public class Example { } public class Example{ public void sample(){ System.out.println("sample method of the Example class"); } public void demo(){ System.out.println("demo method of the Example class"); } public static void main(String args[]){ Example obj = new Example(); obj.sample(); obj.demo(); } } 

Error

 C:\Sample>javac Example.java Example.java:6: error: duplicate class: Example public class Example{ ^ 1 error 

In fact, you can't create two public classes in a single file, Only one class should be public and it should be the name of the class.

If you try to create two public classes in same file the compiler generates a compile time error.

Example

 public class Sample { } public class Example{ public void sample(){ System.out.println("sample method of the Example class"); } public void demo(){ System.out.println("demo method of the Example class"); } public static void main(String args[]){ Example obj = new Example(); obj.sample(); obj.demo(); } } 

Error

 C:\Sample>javac Example.java Example.java:2: error: class Sample is public, should be declared in a file named Sample.java public class Sample { ^ 1 error 
Updated on: 2019-07-30T22:30:20+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements