Re: Do some computation before calling super constructor.



"Oliver Wong" <owong@xxxxxxxxxxxxxx> wrote in
RJoGf.184829$AP5.103980@edtnps84:">news:RJoGf.184829$AP5.103980@edtnps84:


"Fabien Bergeret" <fabien.bergeret@xxxxxxxxxxxxxxxxxxxxxx> wrote in
message news:43ea0ac1$0$763$636a15ce@xxxxxxxxxxxxxxx

In a constructor, the super call MUST be the first line of your code.
Therefore, you cannot call super after having made some computations.
What you can do in State :

public class State {
public State(){
}
public State(String name) {
super();
init(name);
}
protected void init(String name) {
this.name = name;
}
[...]

Some people claim you should never call methods that can be
overridden
from a constructor. I saw an example illustrating why this was
important, but I can't recall it off the top of my head right now.

Imagine that a subclass (class SubState extends State ...) overrides a
method used in the constructor. I believe what happens is that when the
superclass gets constructed, the new method gets used instead of the
original (now overriden) method. Thus the superclass does not get
initialized as expected. Furthermore, the new method may make use of
fields in the subclass that have not yet been initialized. This could be
very ugly.

This can be avoided by making "final" any methods used by a constructor.
The subclass cannot override a final method.

Did I get this right?


--
Ian Shef 805/F6 * These are my personal opinions
Raytheon Company * and not those of my employer.
PO Box 11337 *
Tucson, AZ 85734-1337 *
.



Relevant Pages

  • Re: Inheritance and static protected constants
    ... >>protected instance variable to this constant's value in the constructor. ... >>One concrete class that extends the base class and overrides the constant. ... >>public class Concrete extends AbstractClass { ... It will work if it is acceptable for the subclass to change the ...
    (comp.lang.java.programmer)
  • Re: Constructor Chaining Conundrum
    ... that is not overriden by the child. ... s in Derived *shadows* s in Base, ... printin Derived *overrides* printin Base; ... constructor calls print, Derived's printwill be called (we are ...
    (comp.lang.java.programmer)
  • Re: Can a classs constructor call another constructor "later"?
    ... I find the current constructor behaviour ... with "constructor overrides behave in the opposite way to method ... choose to call the base method wherever you like, ... I should point out that what Alex did in his first example ...
    (microsoft.public.dotnet.csharp.general)
  • Re: Extend a class without calling the constructor
    ... I plan to do this by creating a class B which extends A, and overrides the method. ... really have to then make the overriding method correct even before you constructor has executed. ... There are hacks with thread-locals, synchronised statics or inner classes to hand context information over. ...
    (comp.lang.java.programmer)