Path: csiph.com!usenet.pasdenom.info!gegeweb.org!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: why does this work? Date: Wed, 08 Aug 2012 14:03:48 -0400 Organization: A noiseless patient Spider Lines: 52 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Wed, 8 Aug 2012 18:03:51 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="d3779b2c4a3397eb5709eec94bad057a"; logging-data="2238"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19DJUbzYAATizDEapfJq+Wh" User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20120713 Thunderbird/14.0 In-Reply-To: Cancel-Lock: sha1:vH3MmA/3f08WOioxjUZc0q/KGV4= Xref: csiph.com comp.lang.java.programmer:17362 On 8/8/2012 1:30 PM, dkoleary wrote: > [...] > How come that isn't recursive? XCopy.main() instantiates a new XCopy. Shouldn't that new XCopy instance also instantiate a new XCopy? See Daniel Pitts' explanation. Another thing you could try to help you see what's going on is to sprinkle some more println() calls through the code to help trace through the execution. In this case you're interested in where the constructor fits with relation to everything else, but there's no explicit constructor written in the code. As I'm sure you've learned, this means the compiler will write a simple constructor for you -- but there's no way to get the compiler to stick println() calls in what it writes, so your recourse is to write your own explicit constructor. With this in mind, the code might look like: class XCopy { public static void main(String[] args) { System.out.println("entering main()"); int orig = 42; System.out.println("main() creates an XCopy"); XCopy x = new XCopy(); System.out.println("main() created an XCopy"); int y = x.go(orig); System.out.println(orig + " " + y); System.out.println("main() is finished"); } int go(int arg) { System.out.println("executing go(), arg = " + arg); return arg * 2; } // Explicit constructor, just for the println XCopy() { System.out.println("constructing an XCopy"); } } Run this version, study the output, and see if the sequence of events becomes clearer. This technique is sometimes called "printf debugging" (the name comes from a different programming language). Despite its simplicity, it can be astonishingly effective, and the overall approach can be used in most environments and most languages. Indeed, Java's various logging frameworks (you may learn about them later) are basically just fancied-up versions of printf debugging: A piece of the program blurts "Look! I'm *here*, and these are a few interesting values." -- Eric Sosman esosman@ieee-dot-org.invalid