Hello,
Is it possible to use a constant in a constructor ?
Code:private final String X = "x";
public Y() {
this(X);
}
Each time i get an error message :
Cannot reference X before supertype constructor has been called
Kind regards
Printable View
Hello,
Is it possible to use a constant in a constructor ?
Code:private final String X = "x";
public Y() {
this(X);
}
Each time i get an error message :
Cannot reference X before supertype constructor has been called
Kind regards
your code does not make any sense.
Well, seemingly not.
Not like this you can't.
Until the parent constructor has been called you can't use any attributes of the child since the object hasn't been built yet, so those attributes don't really exist.
What is it you are trying to achieve? A default value to use if the empty constructor is called? If so then make X static.
Hi,
adding static solved my problem.Quote:
A default value to use if the empty constructor is called? If so then make X static.
thx.
Well, it solves your problem if my assumption of what you were trying to do was correct.
Otherwise it might simply be a hack.
Hi Tolls,
Your assumption was correct.
Thanks a lot
Dipke
Objects are like onions; they are constructed inner layers (superclass) first, outer layers (subclass) last. The compiler helps you (halfway) with this: a constructor should either have a call to this( ... ) (another constructor from the current class) or to super( ... ) (a constructor of the superclass). If you don't put a call to a super( ... ) constructor and if you don't have a this( ... ) call the compiler puts a call to the no-arg constructor there: super(). If all your constructors call another constructor from the same class the compiler flags it as an error.
Only when the superclass constructor has finished the member variables of the current (subclass) are initialized. Before that moment the compiler forbids you to refer to any of them.
I wrote 'the compiler helps you halfway' because a constructor (in a superclass) can call methods that are overridable. If such a method is overridden the overriding method will be called (in a subclass). I consider that an anomaly of the language implementation but I do understand why it was done that way. (let a heated discussion commence! ;-)
kind regards,
Jos
Hi JosAh,
Thanks for the explanation.
That is then also the reason why a setter must be final when used in constructor ?
Grz
Dimi