-1

I have 2 classes in a single Java source file, and the name of the source file is the same as the public class. When I run the source file, I get the following error:

enter image description here

 package inheritance;

 class clsnae {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("first");
    }
}

  public  class clsname {

     public static void main(String[] args) {
            // TODO Auto-generated method stub
            System.out.println("second");
     }
}
  1. May I know why my compiler or JRE can't find my other file (non-public file)?
  2. If I remove the public keyword, it just prints "first" and not "second", but after adding the public keyword to the class name, why does it still try to run the first class instead of running the second class?
0xCursor
  • 2,242
  • 4
  • 15
  • 33
  • post your code instead of screenshot and format your code. – Shanu Gupta Jun 09 '18 at 05:45
  • 1
    I am not how you are running your program but I have tried the same example it is working fine. Eclipse asking me which class with the main method I want to execute and a pop comes with the selectable option. – Amit Bera Jun 09 '18 at 05:54

2 Answers2

2

Your code is fine. There are two main methods and you can run any of them at a time.

For the first time eclipse would ask you which main method to run. If you want to change later, you can modify your run configurations and choose your main class.

Goto Run configurations: enter image description here

and then choose the main class:

enter image description here

Here's the sample run:

enter image description here

Shanu Gupta
  • 3,699
  • 2
  • 19
  • 29
0

This has more to do with Java Specification. The rule says if you are declaring a class as public the name of the file in which the class resides MUST have the same name.

However, The same rule doesn't apply if you don't specify the public modifier while defining your class. so you can save the file using any classname.

In your case Rule 1 violates.

For more details: Refer to the following answer: Why are filenames in Java the same as the public class name?

Since there are two main methods the Eclipse will prompt you with the classes having the main method to execute. in the current class.

enter image description here

Yati Sawhney
  • 1,372
  • 1
  • 12
  • 19
  • 3
    how does it violate rule 1, my source file name is same as my public class name. –  Jun 09 '18 at 05:51
  • Lol! You just modified it before taking the screenshot. Just read the error message! The class name is different. Run it again – Yati Sawhney Jun 09 '18 at 05:53
  • `"inheritence.clsnme"` instead of `"inheritence.clsname"` – Yati Sawhney Jun 09 '18 at 05:54
  • i didnt modify anything , my source code file name is `clsname` and my public class file name is `clsname`. if i did modify u can still see the edit history. –  Jun 09 '18 at 05:57