I want to do some initialization in child class constructor and pass result to super()
.
But Java doesn't allow any processing in child class constructor before super()
call.
Whats a good way to solve this problem?
I want to do some initialization in child class constructor and pass result to super()
.
But Java doesn't allow any processing in child class constructor before super()
call.
Whats a good way to solve this problem?
The bad news is that you can't.
The good news is that you can.
How you cannot:
How you can:
To solve that situation, don't use inheritance, use composition. But take in mind that both A and B shouldn't depend on each other. Both should depend on an abstraction (for example an interface) that both (or maybe just A) implement.
Strictly speaking this is not composition but aggregation but, in a loose way of speaking, we are using composition instead of inheritance.
==> I.java <==
public interface I {
public void setChild(I i);
public void setParent(I i);
public void setX(String s);
public void setY(int n);
public void setZ(boolean b);
}
==> A.java <==
/* This class is abstract only for Eclipse to allow me
to leave out all the method stubs
for the sake of conciseness of the example
(I like my examples to compile) */
public abstract class A implements I {
private I child;
@Override
public void setChild(I i) {
this.child= i;
this.child.setParent(this);
}
}
==> B.java <==
/* This class is abstract only for Eclipse to allow me
to leave out all the method stubs
for the sake of conciseness of the example
(I like my examples to compile) */
public abstract class B implements I {
private I parent;
@Override
public void setParent(I i) {
this.parent = i;
// now modify the state of the "parent"
this.parent.setX("Answer to the Ultimate Question of Life, The Universe, and Everything");
this.parent.setY(42);
this.parent.setZ(true);
}
}
I would favour composition over inheritance, and do something like:
public class Super(Child child) {
}
(naming for consistency with the question above - not good otherwise) and inject the class dependency in. Relying on construction order in an inheritance hierarchy is difficult, problematic and doesn't allow a subsequent decomposition/disentanglement of the dependent classes.
As soon as I find myself in such a situation, I take a step back and ask what I'm really trying to achieve. The result (most usually) looks like the above.