Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!news.nobody.at!texta.sil.at!newscore.univie.ac.at!aconews-feed.univie.ac.at!aconews.univie.ac.at!not-for-mail Newsgroups: comp.lang.java.programmer From: Andreas Leitgeb Subject: Re: calling own methods from constructor References: <2011040622233261380-angrybaldguy@gmailcom> Reply-To: avl@logic.at User-Agent: slrn/pre0.9.9-111 (Linux) Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Message-ID: Date: 07 Apr 2011 09:13:56 GMT Lines: 39 NNTP-Posting-Host: gamma.logic.tuwien.ac.at X-Trace: 1302167636 tunews.univie.ac.at 60386 128.130.175.3 X-Complaints-To: abuse@tuwien.ac.at Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:2917 Owen Jacobson wrote: > On 2011-04-06 16:48:41 -0400, Andreas Leitgeb said: > >> There is well-known danger in calling own methods from the >> constructor, namely that the method called may be overridden >> by a subclass, which is really instanciated, but whose specific >> constructor has not yet been run. >> >> I do not intend to delve into the details of static, private >> or final methods, or final'ity of the class itself (and maybe >> others) avoiding these problems, but instead I'm curious, why >> Java just doesn't simply forbid the dangerous calls. > > It's hard to prove that a constructor never calls a virtual method. Consider: > [ example of c'tor calling a private method "internalInit", which in turn > calls virtual "virtualMethod". ] Good point. The compiler couldn't (at least not statically) prevent indirect calling of overridable non-static methods. But otoh., it refuses to compile this: String bad = (String) new Integer(42); while allowing this: (sure bomb at runtime) String bad = (String) (Object) new Integer(42); So, not being able to prevent something happening indirectly, doesn't imply that the direct way would need to be allowed, too. So, it boils down to the original question of whether there is also a good use of constructors (directly or indirectly) invoking overridable virtual methods. What it "good"? I have no exact definition, but if one of the Java gurus (Brian Goetz, Joshua Bloch, James Gosling,...) ever before suggested a pattern that would involve it, then chances are good, that I'd accept it. Also, if the JSL or one of the big Java-based projects used it. Tom's example (Library) didn't convince me so far.