I know this was posted a long time ago.. but I just now stumbled upon this
So there was this question on 1st page of this thread:
Sweetpin2 wrote:But When we put below code in Sub class itself
public static void main(String[] args){
System.out.println(Sub.ID);
}
it prints In SubQBANK, why so?
And admin response was:
admin wrote:Because when you do Sub.ID, you are refering to the class Sub, and so Sub's static initialize is run, which prints "In Sub" and then QBANK is printed.
Well... I must say.. this answer may not be quite true.
First of all, as Sweetpin2 stated, he just copied code (main method) from class Test to class Sub so now we have 2 (equal) main methods in file (one in Sub and one in Test class). When we compile this file (e.g. run "javac Test.java" in cmd on Windows, in case file is saved as Test.java) we will get 3 .class files. Two of them (Sub.class and Test.class) have main methods.
Now, when we run main from Test (e.g. run "java test.Test" in cmd on Windows) we get "QBANK" as output. Just like answer of OCA question says.
But if we run main from Sub (e.g. run "java test.Sub" in cmd on Windows) we get "In SubQBANK" as output. And now.. this is what user Sweetpin2 noticed. But reason for this behavior is quite different, in my opinion.
The simplest explanation for this is that, when main method is executed in Sub class, that class gets loaded (instead of Test class, so "In Sub" gets printed) and only after that, Sub.ID is printed. In case method from Test class is run, class Sub is never loaded so "In Sub" is never printed. In both cases main method calls "System.out.println(Sub.ID);" so they are both refereing to class Sub but this has actually no effect on outcome in this case.
Note that this can easily can be tested in some IDE (like Eclipse) since IDE can automatically detect two main methods. When user asks IDE to run code as java Application it will ask user to specify main method to run (int this case: "Sub-test" and Test-test") and output will depend on user choice.
Sorry for long post.
And correct me if I am wrong