Reputation: 5235
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.
Upvotes: 0
Views: 109
Reputation: 699
Calling abstract method in a constructor is a bad design. Some tools like PMD indicates it as warning by default (or maybe even error). So it's hard to talk about any pattern here I think. What i would do is to implement Bar class as below.
public class Bar extends Foo{
private int aValue;
private boolean initialized = false;
public Bar(int aValue){
this.aValue = aValue;
initialized = true;
register();
}
public void register(){
if (initialized)
aMethod(aValue);
}
}
Upvotes: 0
Reputation: 19185
Your class structure is pretty messed up. Do you have something this in legacy code that you cannot change parent ? If not change it:-)
Upvotes: 0
Reputation: 1500675
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.
Upvotes: 2