A coworker (who is very new to Java) stopped in today and asked what seemed like a very simple question. Unfortunately, I did an absolutely horrible job of trying to explain it to him. He had a book that had a little code that looked like this:
class XCopy {
public static void main(String[] args) {
XCopy x = new XCopy(); // 1
x.doIt();
}
public void doIt() {
// Some code...
}
}
He was confused on line 1. What he wanted to know was why a new instance of XCopy could be created within the definition of the class XCopy. He thought this would have given some sort of a forward referencing error. After all, we hadn’t yet finished declaring what the class XCopy was, so how could we create one?
I certainly know that this is valid code but, when I tried to explain it to him, I found myself stumbling over the answer and I’m afraid I left him more confused than when he started. I’d like to hear some other explanations of why this works.
Any thoughts? Why can you instantiate an instance of a class within the definition of the class, itself?
You are defining the class, all its fields and methods etc at compile time. The instance is not created until runtime. So there is no contradiction, the class is fully defined by the time you reach line #1.
As others point out, because the
mainmethod isstaticyou will reach line #1 without having instantiated an object, but you can do so without issue. I use this pattern all the time for one-class experiments.