C
Christian Pontesegger
Hi all,
for a recent project I was trying to initialize members of a derived
class from the constructor of the super class (done using an abstract
method). This is an example code:
public abstract class Base {
public Base() {
init();
}
protected abstract void init();
}
public class Derived extends Base {
private int foo = 0;
public Derived() {
super();
}
protected void init() {
foo = 5;
}
public static void main(String[] argv) {
System.out.println((new Derived()).foo);
}
}
Running this example will print "0". As I understand it Base calls
Derived.init, which sets the value to 5. Afterwards the constructor of
Derived is called and foo is reinitialized. This seems strange to me. I
expected either initialization of all members done before any
constructor is called or an error when trying to access a member which
isn't properly initialized.
Now I know how to get my intended behavior, just don't initialize foo =
"0" and this program will return "5" as expected (at least by me).
But is this behavior mentioned above a design problem or is it even
useful and I can't see the meaning of it?
thanks
Christian Pontesegger
for a recent project I was trying to initialize members of a derived
class from the constructor of the super class (done using an abstract
method). This is an example code:
public abstract class Base {
public Base() {
init();
}
protected abstract void init();
}
public class Derived extends Base {
private int foo = 0;
public Derived() {
super();
}
protected void init() {
foo = 5;
}
public static void main(String[] argv) {
System.out.println((new Derived()).foo);
}
}
Running this example will print "0". As I understand it Base calls
Derived.init, which sets the value to 5. Afterwards the constructor of
Derived is called and foo is reinitialized. This seems strange to me. I
expected either initialization of all members done before any
constructor is called or an error when trying to access a member which
isn't properly initialized.
Now I know how to get my intended behavior, just don't initialize foo =
"0" and this program will return "5" as expected (at least by me).
But is this behavior mentioned above a design problem or is it even
useful and I can't see the meaning of it?
thanks
Christian Pontesegger