Why Class B can't become public? How can I use class be in other classes? Is it better to define it inside Cons?!
// public class B { why not?
class B {
int x;
B (int n) {
x=n;
System.out.println("constructor 'B (int n)' called!");
}
}
public class Cons {
public static void main(String[] args) {B b = new B();}
}
No, while defining multiple classes in a single Java file you need to make sure that only one class among them is public. If you have more than one public classes a single file a compile-time error will be generated.
So when we provide more than one public class in a program the compiler itself stops you by throwing an error. This is because later we can't confuse the JVM as to which class is to be its initial class, because only one public class with the public static void main(String args[]) is the initial class for JVM.
A single Java program can contain more than one class and there are no restrictions on the number of classes that can be present in one Java program. But each Java program should have one class declared as public to make it accessible for classes in a different package.
Yes, we can have multiple classes in same java file. But, there is one restriction over here, which is that you can have as many classes in one file but only one public class is allowed. If we try to declare 2 classes as public in the same file, the code will not compile.
As per java language specification, there can be only one public class in a file (.java) and file name should be same as public class name.
If you want class B accessible in other placs, you may create a separate B.java file and move your Class B code to that file.
This thread may give you some more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With