I am new to Java programming, i created one class with name as Demo and saved as sample.java while compile this java program it giving compilation error as below
public class Demo {
public static void main(String[] args) {
System.out.println("This is year");
}
}
sample.java:3: class Demo is public, should be declared in a file named Demo .java
why do we declare public classes in individual files……
Thanks
Mukthyar
@Oli Charlesworth is right: this is required by Java language specification. You can probably ask why do they require this? The possible answer is to make things clear. Class is atomic unit by definition. You can replace class by its other version and if the public interface was not changed everything will continue working.
So, Java language designers decided to force us to store each classes in separate files.
They just did some exception for non-public classes. Several non-public classes can be saved in one file. I think that the reason is that non-public class is a kind of gory details of the implementation that can be changed at any time by author. Since class is non-public these changes should not affect any API user.
But I strongly recommend you to save every class (even if it is not public) in separate file. This improves code readability and in the end of the day its quality.