I declared the following class
class A { //not public
public static void main(String args[]) {
System.out.println(\"done\");
}
When
The reason the JVM can see a non-public class is because it controls visibility, meaning it sees everything and decides what can see/call/access what.
The use of public
on a class is different than on a method, but the concept is the same.
On a method, the public
keyword means the method can be used outside the class. An example would be:
class A {
public static void do() {
// Do something
}
}
class B {
public static void main(String[] args) {
A.do(); // This works because do() is public and static
}
}
The same concept applies to classes, but in a different way.
Using public
on a class means that it can be used outside the current .java
file (it will have its own .class
file).
Here's an example:
//C.java
class C {
static void do() {
// Do something
}
public static void run() {
A.do(); // Works because A.do() is public and static
B.do(); // Does not work because B is not a public class
}
}
//A.java
public class A {
public static void main(String[] args) {
B.do(); // Works because B is in the same file
do(); // Duh...
}
public static void do() {
// Do something
}
}
class B {
static void do() {
// Do something
}
}