Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > calling own methods from constructor

Reply
Thread Tools

calling own methods from constructor

 
 
Paul Cager
Guest
Posts: n/a
 
      04-07-2011
On Apr 7, 9:36*am, Andreas Leitgeb <(E-Mail Removed)>
wrote:
....
> I'd say, that they exist for any reasonable specification of the problem,
> and "back it up"(*) by declaring specifications for which no (or only
> mindboggingly contrived) alternatives exist as unreasonable
>
> (*): In German, we use double-quotes also to indicate tongue-in-cheek
> formulations that aren't to be taken entirely literally/serious.
> I've recently learned that they are not always thusly understood,
> elsewhere. *Therefore this explanation. Is there any common markup
> for it that would be recognized in the English-speaking world?


I think we use the same convention in British English. I'm not certain
about our "colonial cousins".

The convention also spills over into spoken English, often using non-
verbal hints. There was also a fad at one time for people to raise
their hands to either side of their head and wriggle two fingers to
imitate quotes. I believe it's only used ironically now.
 
Reply With Quote
 
 
 
 
Tobias Blass
Guest
Posts: n/a
 
      04-07-2011
On 2011-04-07, Andreas Leitgeb <(E-Mail Removed)> wrote:
> Owen Jacobson <(E-Mail Removed)> 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.
>

Why should it complain about your second example? You tell the Compiler
explicitly "Please consider this Integer as Object and this Object as String,
I know types don't match but I know what I'm doing" (I'm programming in C at
the moment where the Compiler doesn't complain about things javac wouldn't
even compile as in your first example, so YMMV)
 
Reply With Quote
 
 
 
 
Robert Klemme
Guest
Posts: n/a
 
      04-07-2011
On 7 Apr., 10:44, Andreas Leitgeb <(E-Mail Removed)>
wrote:
> Lew <(E-Mail Removed)> wrote:
> > Andreas Leitgeb wrote:
> >>> 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?

>
> > import org.apache.log4j.Logger;
> > import static org.apache.log4j.getLogger;
> > public class Foo
> > {
> > * * private final Logger logger = getLogger( getClass() );
> > * // ...
> > }

>
> I thought, I made it clear, that calling static methods was not relevant
> to my question. *So, kind of thanks for pointing out that I should have
> written non-static in the very line of the question, rather than consider
> that clear from the other (snipped by you) paragraphs of my post...


Well, that is clear, but: getClass() isn't a static method. Note that
Lew did not post the usual idiom with log4j and the like which
typically looks something like this:

private static final Logger logger = Logger.getLogger(Foo.class);

As for me, I can't remember having shot myself in the foot with this
feature of Java (i.e. allowing to invoke virtual methods in
constructor). I reckon, language designers figured that allowing it
is more worthwhile than preventing it. As Thomas pointed out you
would have to provide constructor arguments so subclasses can pass on
data they have created. This is tiresome and may even end up being
inefficient namely in the case where the superclass constructor needs
to decide which methods to call (or whether methods to call). You
would end up creating objects which then need to be discarded if the
super class constructor decides that he does not need them =>
inefficient code.

Btw, the check would be expensive for the compiler and I am also not
sure how that byte code might look like because you need to extend the
restrictions to all methods. Consider

class Foo {
private int v;

public Foo() {
v = init(); // allowed, because it's private
}

public void reinitialize() {
v = init();
}

private int init() {
// allowed, but only if init() is not invoked
// from a constructor:
int x = doSomething();
return x * 10 + 2;
}

/** Sub classes may override this.
* @return a number
*/
protected int doSomething() {
return 5;
}
}


Kind regards

robert
 
Reply With Quote
 
Lew
Guest
Posts: n/a
 
      04-07-2011
On 04/07/2011 04:44 AM, Andreas Leitgeb wrote:
> Lew<(E-Mail Removed)> wrote:
>> Andreas Leitgeb wrote:
>>>> 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?

>>
>> import org.apache.log4j.Logger;
>> import static org.apache.log4j.getLogger;
>> public class Foo
>> {
>> private final Logger logger = getLogger( getClass() );
>> // ...
>> }

>
> I thought, I made it clear, that calling static methods was not relevant
> to my question. So, kind of thanks for pointing out that I should have
> written non-static in the very line of the question, rather than consider
> that clear from the other (snipped by you) paragraphs of my post...


I did not realize that 'getClass()' was static.

--
Lew
Honi soit qui mal y pense.
http://upload.wikimedia.org/wikipedi.../c/cf/Friz.jpg
 
Reply With Quote
 
Andreas Leitgeb
Guest
Posts: n/a
 
      04-07-2011
Arved Sandstrom <(E-Mail Removed)> wrote:
> On 11-04-07 05:36 AM, Andreas Leitgeb wrote:
>> (*): In German, we use double-quotes also to indicate tongue-in-cheek
>> formulations that aren't to be taken entirely literally/serious.
>> I've recently learned that they are not always thusly understood,
>> elsewhere. Therefore this explanation. Is there any common markup
>> for it that would be recognized in the English-speaking world?

>
> It would be quotation marks, usually double quotes, just as in German.
> Even Wikipedia (in its entry for Quotation Marks) refers to the use of
> quotation not only for actual quotes, but also to denote irony or
> unusual usage. Quotes are also used to indicate non-literal or
> self-coined meanings, or to emphasize use of the word rather than its
> meaning.


Thanks for the info!

> Having said that, there are varying levels of literacy in the
> English-speaking world. Not everyone will be aware of the other
> usages for quotation marks.


:/

 
Reply With Quote
 
Andreas Leitgeb
Guest
Posts: n/a
 
      04-07-2011
Roedy Green <(E-Mail Removed)> wrote:
> On 06 Apr 2011 20:48:41 GMT, Andreas Leitgeb
><(E-Mail Removed)> wrote, quoted or indirectly quoted
> someone who said :
>
>> Is there any *good* use of having the constructor call a method
>> that actually *can* be overridden in a subclass?

>
> I have accidentally nailed myself by overriding a method used in a
> constructor. I have yet to find a legitimate use for it. It is too
> bad the compiler does not complain about it.


I haven't (yet) been bitten by it, myself.
I just recently came to think about it.

 
Reply With Quote
 
Andreas Leitgeb
Guest
Posts: n/a
 
      04-07-2011
Paul Cager <(E-Mail Removed)> wrote:
>> (*): In German, we use double-quotes also to indicate tongue-in-cheek
>> formulations that aren't to be taken entirely literally/serious.

> I think we use the same convention in British English. I'm not certain
> about our "colonial cousins".



> The convention also spills over into spoken English, often using non-
> verbal hints. There was also a fad at one time for people to raise
> their hands to either side of their head and wriggle two fingers to
> imitate quotes. I believe it's only used ironically now.


Is that a consequence of the "Austin Powers" movies, or did the
movies only make fun of an already common behavioural pattern?

 
Reply With Quote
 
Andreas Leitgeb
Guest
Posts: n/a
 
      04-07-2011
Tobias Blass <(E-Mail Removed)> wrote:
>>> 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);


> Why should it complain about your second example? You tell the Compiler
> explicitly "Please consider this Integer as Object and this Object as String,


It wasn't my intention to criticize that double-casts are allowed,
nor that single casts of incompatible types aren't. Just, that there
already is an example of something bad, that is indirectly possible
but directly forbidden.

> I know types don't match but I know what I'm doing"


Interestingly, those cases where such a double cast would
solve a real problem (namely casting between two interfaces
or between a non-final class and an interface & vice versa)
do already work with a single cast, so I don't really understand,
what double casts are really good for.

> (I'm programming in C at the moment where the Compiler doesn't
> complain about things javac wouldn't even compile as in your
> first example, so YMMV)


Casting in C++ is something different than in Java.
Although, if you really do C, not C++, then it's it's
much more like Java, except for the lacking safety net.

I'm doing C++, and recently I noticed a mistake of mine on
rereading it: I had tried to use polymorphism with objects
stored directly in an stl vector<baseclass>...
Changed it to vector<const baseclass*>, a few "."s to "->"s, and
added a few "new"s, allowing me to continue using polymorphism.
(The vector isn't meant to ever shrink till end of process, so no
extra "delete"s. Also, it only grows during initialization.)

 
Reply With Quote
 
Andreas Leitgeb
Guest
Posts: n/a
 
      04-07-2011
Lew <(E-Mail Removed)> wrote:
> On 04/07/2011 04:44 AM, Andreas Leitgeb wrote:
>> Lew<(E-Mail Removed)> wrote:
>>> Andreas Leitgeb wrote:
>>>>> 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?
>>> private final Logger logger = getLogger( getClass() );

>> I thought, I made it clear, that calling static methods was not relevant
>> to my question. So, kind of thanks for pointing out that I should have
>> written non-static in the very line of the question, rather than consider
>> that clear from the other (snipped by you) paragraphs of my post...

>
> I did not realize that 'getClass()' was static.


I did not realize that getClass() was overidable - a property I even
explicitly repeated in my question. For this, I assumed you were
talking of getLogger().

 
Reply With Quote
 
Andreas Leitgeb
Guest
Posts: n/a
 
      04-07-2011
Robert Klemme <(E-Mail Removed)> wrote:
> On 7 Apr., 10:44, Andreas Leitgeb <(E-Mail Removed)>
> wrote:
>> Lew <(E-Mail Removed)> wrote:
>> > Andreas Leitgeb wrote:
>> >>> 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?

>>
>> > import org.apache.log4j.Logger;
>> > import static org.apache.log4j.getLogger;
>> > public class Foo
>> > {
>> > * * private final Logger logger = getLogger( getClass() );
>> > * // ...
>> > }

>>
>> I thought, I made it clear, that calling static methods was not relevant
>> to my question. *So, kind of thanks for pointing out that I should have
>> written non-static in the very line of the question, rather than consider
>> that clear from the other (snipped by you) paragraphs of my post...

>
> Well, that is clear, but: getClass() isn't a static method.


Because getClass() is final, it didn't occur to me, that he
would have put up *that* as an example...

> As for me, I can't remember having shot myself in the foot with this
> feature of Java (i.e. allowing to invoke virtual methods in
> constructor). I reckon, language designers figured that allowing it
> is more worthwhile than preventing it. As Thomas pointed out you
> would have to provide constructor arguments so subclasses can pass on
> data they have created. This is tiresome and may even end up being
> inefficient namely in the case where the superclass constructor needs
> to decide which methods to call (or whether methods to call). You
> would end up creating objects which then need to be discarded if the
> super class constructor decides that he does not need them =>
> inefficient code.


The example of that Library class-hierarchy looked a bit
contrived to me.

> Btw, the check would be expensive for the compiler and I am also not
> sure how that byte code might look like because you need to extend the
> restrictions to all methods. [...]


It would be already an improvement, if direct calls to such
methods from the constructor were forbidden.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
own initialization before calling parent's constructor avasilev C++ 23 12-09-2011 01:54 PM
A constructor calling another constructor (default constructor)? Generic Usenet Account C++ 10 11-28-2007 04:12 AM
Avoid calling non-final methods in a constructor: Applies to static methods too? Oliver Wong Java 14 06-13-2006 09:18 AM
Calling own-constructors inside another constructor EdUarDo Java 4 12-21-2005 12:23 PM
why it's not possible calling constructor from constructor? Giulio C++ 9 06-25-2003 03:56 PM



Advertisments