a child class extending a mother class which, in its constructor call a template method instianted in the child class because it need a value obtained in the child constructor.
How Can I do something like this, without changing my Parent constructor (Foo, here. I cannot do any changes in the real Foo class):
public abstract class Foo{
public Foo(){
register();
}
public abstract void register();
public void aMethod(int aValue){
// body
}
}
public class Bar extends Foo{
public Foo(int aValue){
// body
}
register(){
aMethod(aValue);
}
}
Here, even if I put aValue in a field, aValue is not even created at
aMethod(aValue);.
How can I solve my problem?
I am looking for any pattern, ULM, solution.
a child class extending a mother class which, in its constructor call a template method instianted in the child class because it need a value obtained in the child constructor.
Why doesn't the subclass constructor simply pass the value up to the superclass constructor?
public abstract class Foo {
protected Foo(int value) {
... use value ...
}
}
public class Bar extends Foo {
public Foo(int value) {
super(value);
}
...
}
Note that calling virtual methods in a constructor is a dangerous practice, as the subclass won't have had the opportunity to initialize itself yet.