Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Daniele Futtorovic Newsgroups: comp.lang.java.programmer Subject: Re: calling own methods from constructor Date: Fri, 08 Apr 2011 01:51:29 +0200 Organization: A noiseless patient Spider Lines: 64 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Thu, 7 Apr 2011 23:51:26 +0000 (UTC) Injection-Info: mx02.eternal-september.org; posting-host="mq2fJvvOLkPF7uVaTA54qg"; logging-data="26818"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/1jAs7jSbFYD45wTdM5lZS" User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.15) Gecko/20110303 Thunderbird/3.1.9 In-Reply-To: Cancel-Lock: sha1:7qIVJk9VT8LLDS2iCiWZpP4C3O8= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:2957 On 06/04/2011 22:48, Andreas Leitgeb allegedly wrote: > 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. Definitely present. > Is there any *good* use of having the constructor call a method that > actually *can* be overridden in a subclass? I mean, are there > (non-anti)patterns of explicitly allowing subclasses to hook into > base-class's construction? I've recently written something like this: class BaseClass implements java.io.Externalizable { protected Map store; protected BaseClass( Map store ){ this.store = store; initialise0(); } public BaseClass(){ } //needed for Externalizable protected void initialise0(){} public void readExternal( ObjectInput input ){ this.store = (Map) input.readObject(); initialise0(); } } class SubClass { private static final Object KEY = ... String datum; public SubClass( Map store ){ super( store ); } protected void initialise0(){ super.initialise0(); datum = (String) store.get( KEY ); } } I consider this a valid use. Sure, even at this basic level you need to be careful, especially if you get back to the code after a while and start extending the hierarchy. I could have duplicated the initialisation code in the (Map) c'tor. I'm not very fond of big c'tors however, and even less fond of code duplication. So there. As for the fact that you can call virtual methods, I'm all for it, just as I am against any sensible restriction. We're all adults (probably) and know what we're doing (mostly), and anyway there's already so many more places you can screw up if you're not careful (autoboxing comes to mind) -- I generally pay a lot more attention when I craft a class hierarchy than when I write a single statement involving primitives and Objects at the same time. -- DF. An escaped convict once said to me: "Alcatraz is the place to be"