0

I know that in java the file name should always be same with class name.Suppose if the file name is test.java then the class name should be test.

But after I read this site question 8 tells that we can have empty class name.

Indirectly this means that file name is different from class name.

So I got confused and again searched in the internet and found these links Why are filenames in Java the same as the class name? and Can I compile a java file with a different name than the class?

Both says that class name should be equal to file name.

After that I tried to create a empty file in eclipse but its not allowing me.If do not enter file name then the finish button is not getting enabled.

Can anybody please tell me is the answer given in the webiste is right or wrong?

Note I know we can have different class name as that of file name provided that class should not be public .If the class is not public and file name is different from class name then JVM can not find main method

Community
  • 1
  • 1
rocking
  • 4,729
  • 9
  • 30
  • 45

2 Answers2

1

What they're claiming is that .java is a legal java source file name, and that the resulting .class file name will be taken from the name of the class as stated in the source.

This may be true. But frankly, if any interviewer asks you this trick question, the right answer is "perhaps, but it would be horribly bad practice."

keshlam
  • 7,931
  • 2
  • 19
  • 33
  • Thanks for the answer but can JVM find main method.In eclipse I created class test and after clicking the finish button eclipse gave me public class test.After that I deleted public keyword and renamed test to test1 and saved.Now When I right click then it did not show me run as java application option – rocking Mar 01 '14 at 06:07
  • Not having a public main() is a different question entirely. – keshlam Mar 01 '14 at 06:12
  • I have edited my post and I think you can answer now – rocking Mar 01 '14 at 06:20
  • 1
    If main() is not public, it doesn't meet the requirements for being the program entry point. No matter what the file name is. – keshlam Mar 01 '14 at 06:24
  • main() is public ,class is not public – rocking Mar 01 '14 at 06:25
0

The file name and class name must be same if you declare your class as public, other wise you can have different file name and different class name in the file.

Mohammad Ashfaq
  • 1,333
  • 2
  • 14
  • 38
  • Yes we can have different class name as that of file name is the class is not public.But we can not run because JVM will complain main method not found – rocking Mar 01 '14 at 06:03
  • If you have different class name then you have to compile using the name of the java file and run using name of class. – Mohammad Ashfaq Mar 01 '14 at 06:04