Java – how does a class that references itself work?
•
Java
Suppose we have a class like this:
class XCopy { public static void main(String[] args) { int orig = 42; XCopy x = new Xcopy(); int y = x.go(orig); System.out.println(orig + " " + " y); } }
I know the go method is missing, but it doesn't matter Does this work? It seems so, but I can't picture in my mind how self reference in class works; Does it have any side effects? Why? Isn't this some kind of infinite recursive loop?
Anyway, I just can't figure out how it works; Thank you in advance
Solution
by telephone
XCopy x = new Xcopy();
You are actually calling xcopy's empty constructor instead of calling the main method
So the call looks like:
JVM calls XCopy.main(); main method creates new instance of XCopy by calling XCopy's empty constructor XCopy constructor ends main method ends -> program ends
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码