Constructor Conundrum
- From: Lash Rambo <lr@xxxxxxxxxxxx>
- Date: Wed, 28 Dec 2005 02:04:05 GMT
Say I have two class hierarchies--Problem and Solver--which sketch like
this:
public abstract class AbstractProblem {
private AbstractSolver _solver;
// ...
}
public class ConcreteProblem extends AbstractProblem {
// ...
}
public abstract class AbstractSolver {
public void solve(/* ... */) {
// ...
}
// ...
}
public class ConcreteSolver extends AbstractSolver {
// lots of parameters not in AbstractSolver
// ...
}
ConcreteProblem needs to create a ConcreteSolver and hand it over to
AbstractProblem. The catch is: ConcreteSolver has several parameters
(variables controlling ConcreteProblem's behavior) ConcreteProblem may
want to change from their default values. Changing parameters is
accomplished through accessors.
How can I do this? I've tried...
public abstract class AbstractProblem {
private AbstractSolver _solver;
public AbstractProblem(AbstractSolver solver) {
_solver = solver;
}
// ...
}
public class ConcreteProblem extends AbstractProblem {
ConcreteSolver _cs = new ConcreteSolver();
public ConcreteProblem() {
super(_cs);
_cs.setParam(/* ... */);
}
// ...
}
....but Java won't let me access _cs before AbstractProblem's constructor
has been called.
I'd prefer to keep AbstractProblem's _solver private, since I can't give
subclasses access to it without giving everything else in the package
access to it, which I don't want to do. (Although I guess I could put
the Problem and Solver hierarchies into separate packages with nothing
else in them to approximate subtype-but-not-package access.)
I can't make all of ConcreteSolver's parameters settable via its
constructor, because I may want to change some defaults without changing
others, which I can't always do since Java lacks named parameters (as far
as I know).
Any ideas?
.
- Follow-Ups:
- Re: Constructor Conundrum
- From: PetriSchmitz
- Re: Constructor Conundrum
- From: VisionSet
- Re: Constructor Conundrum
- Prev by Date: Re: frustrating arithmetic
- Next by Date: Thread safe queue
- Previous by thread: eclipse project duplication help
- Next by thread: Re: Constructor Conundrum
- Index(es):