I have never really understood why code such as that given below is valid and would really appreciate it if someone helped me out.
public class A{
int x;
int y;
void hello() {
System.out.println("Hello World");
}
public static void main(String[] args) {
A my_instance = new A();
my_instance.hello();
}
}
OUTPUT:
Hello World
Question: Why are we allowed to create an instance of A inside one of its own static methods?
I understand that static methods belong to the class and not any particular instance, but does this mean that under the hood the compiler first analyzes everything that's not static and makes that code available to static methods?
See if these points help you.
1. Execution of a Java program starts with a special method public static void main(String[] args)
. Since Java is an object oriented language, everything has to be inside class, and this special method main()
is no exception. That's why it is inside a class, namely A
here.
2.
It just seems wrong to me that I can create an instance of something that I'm still in the process of building
This idea of yours is wrong. When the program is running, everything is built already (surely you know the compilation comes before running), so the notion in the process of building doesn't make any sense when the program is already up and running. And if you associate your statement in the process of building to the building of instance of A
, then again that would be wrong, since the main()
method is static, so doesn't require an instance of A
to exist in order for it to be invoked. In fact, main()
is invoked before JVM instantiates any other class in your application.
3.
The main(String[] args)
being the starting point of execution, it must be allowed to instantiate some class. Now, your class A
is a class just like any other, hence main()
can instantiate that too.
Some more reading here: