Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
    Bookmark Topic Watch Topic
  • New Topic

Why the name of the public class should be the name of the file as well  RSS feed

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Report post to moderator
In Java,

When a file contains public class

public class Demo{
}

The code above should be saved with a file name Demo.java


Why it does not get compiled if the file name is not Demo.java ??
Is there any reason for that ??
 
Saloon Keeper
Posts: 8601
161
  • Mark post as helpful
  • send pies
  • Report post to moderator
Yes. This is so the compiler can easily find files when a class from outside the package refers to it. And not only the compiler: imagine how annoying it would be when you're looking for the source code of some class, so you can understand the implementation. You would have to open every file in the package to find the class, or write a program to look for it.
 
Marshal
Posts: 58382
178
  • Mark post as helpful
  • send pies
  • Report post to moderator
If you search, you will find many threads about the same question.
 
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!