Path: csiph.com!x330-a1.tempe.blueboxinc.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!nx02.iad01.newshosting.com!newshosting.com!69.16.185.11.MISMATCH!npeer01.iad.highwinds-media.com!news.highwinds-media.com!feed-me.highwinds-media.com!post01.iad.highwinds-media.com!newsfe17.iad.POSTED!00000000!not-for-mail From: Owen Jacobson Newsgroups: comp.lang.java.programmer Message-ID: <2011040622233261380-angrybaldguy@gmailcom> References: MIME-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1; format=flowed Content-Transfer-Encoding: 8bit Subject: Re: calling own methods from constructor User-Agent: Unison/2.1.4 Lines: 40 X-Complaints-To: abuse@UsenetServer.com NNTP-Posting-Date: Thu, 07 Apr 2011 02:23:32 UTC Date: Wed, 6 Apr 2011 22:23:32 -0400 Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:2909 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: public class Foo { public Foo() { // internalInit is private, therefore final this.internalInit(); } public /* virtual */ void virtualMethod() { System.out.println("Override me! I dare you."); } private void internalInit() { // Whups! 'this' is not always fully initialized. this.virtualMethod(); } } If you forbid internalInit from calling virtual methods because it is, itself, called from a constructor, you also prevent it from calling virtual methods when called from a normal method. If you don't prevent that, but do prevent Foo's constructor from calling any of its own virtual methods, then you end up with the question "why does Java make me use a private method when I want to call a virtual method from a constructor?" instead. -o