Reputation: 51
If I am writing multiple classes on a .java file, do I need at least one public class?
But it compiles if I have more than one class without any public.
class A {
int x=1;
int y=2;
void m1(int i){
System.out.println("i="+i);
}
}
class B extends A{
void m1(int i){
System.out.println("i="+i);
}
}
class test{
public static void main(String args[]){
A a1=new A();
B b1=new B();
System.out.println(b1.x);
System.out.println(a1.y);
//System.out.println(A.y);
a1.m1(4);
}
}
Upvotes: 2
Views: 283
Reputation: 173
My personal preference is to put one class per file, mostly for reading purposes. Only one class can be public per file but you can have as many other classes with less restricting accessors. Also take a look at nested classes maybe thats what you're trying to do.
Take a look at this: How many classes should a programmer put in one file?
Upvotes: 1
Reputation: 3048
The java language specification states:
The access modifier public (§6.6) pertains only to top level classes (§7.6) and to member classes (§8.5), not to local classes (§14.3) or anonymous classes (§15.9.5).
Upvotes: 0
Reputation: 2155
Classes that are public must be implemented in a .java source file with the same name, non-public classes can reside in source files with another name.
Upvotes: 0
Reputation: 206786
No, you do not need to have a public class in any source file.
You can have at most one public class per source file. But it is not required to have at least a public class per source file.
Upvotes: 5