Question

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.

Was it helpful?

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.

OTHER TIPS

Your class structure is pretty messed up. Do you have something this in legacy code that you cannot change parent ? If not change it:-)

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);
    }


}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top