Reputation: 75
As we know we can't create obj of any class until and unless the definition of the class is complete. So how are we able to create obj in main method of its own class?
class Test
{
public static void main(String args[])
{
Test test=new Test(); //yet class definition of Test class is not completed still it is permitted! why?
}
}
Upvotes: 1
Views: 11567
Reputation: 22156
To be fair, "As we know we can't create obj of any class until and unless the definition of the class is complete." is true, but compiling the line
Test test=new Test();
does not create a new object, it says that a new object should be created at runtime.
First you compile the class (which doesn't execute any of the statements inside), then you run it, at which point you're using the compiled class to instantiate (create) a new object.
As a matter of fact, you can create an object in any method of its own class (be it static or instance).
The only problem you should look out for is creating a Test
object in its own constructor. This will end up in a StackOverflowError
, because you will endlessly invoke the constructor recursively.
Upvotes: 17
Reputation: 95489
Java code isn't executed as it is read, but is rather "compiled", so the entire file is seen before it is executed. The Java compiler performs multiple passes over the input, which is why it is possible for a function to invoke another function which is defined beneath it in the same file (whereas, for example, in the C and C++ programming languages, it is necessary to provide a declaration for a function or type before any code is written that instantiates or references that function or type).
Upvotes: 3
Reputation: 1976
Before a object is instancicated , the Class is compleatly load to the Class-Repository of the JVM.
Static methods do not need an instance of the class (as far as its not an inner-class).
Upvotes: 0
Reputation: 4170
how can you decide the definition is not complete??
remember main method is also the part of that class. in above code you can also call the main method using the object of that class.
class Test
{
public static void main(String args[])
{
// whatever code you want
}
}
class Test2
{
public static void main(String args[])
{
// you can call the main method of the Test class
Test obj = new Test();
obj.main(args);
/*
* see when you can call the main method of Test class in class Test2 because
* compiler will treat the **main** as a static method thats it.
*/
}
}
compiler will treat the main as a static method thats it. so when you try to create the object of self class in main method again compiler will treat the main method as a static method (mean definition is there its not the blank class ) so compiler will allow to you to create the object of the self class without any error.
Upvotes: 0