Hi everybody,
I don't know if there is any trick for this. I have a class A and
several classes that inherit from A. Each of these classes should call
always a certain method on its parent A after the constructor has been
called (i.e., after the class is fully initialized). Is there any way
to force this automatically?
No. Why do you want to do this? It sounds to me, perhaps, that you want
to 'fix' the fact that a subclass isn't compelled to call the super
class's constructor by enforcing some setup code elsewhere.... (of
course I may be completely wrong about this!) As Eric asked: what are
you trying to achieve?
Anyway, the fact the you're thinking along these lines indicates to me
that there is something not quite right with the design you have in mind.
It's quite acceptable when designing a class to specify a contract in
the documentation along the lines of 'after constructing this class, you
must call method b() before calling any other methods (e.g. c(), d(), or
e()), or otherwise an exception/undesirable outcome will occur". This
way, you're not *forcing* something to happen, but you're also making it
known (in a reasonable way) what the expected/acceptable interaction
with your class is.
A word of warning - in case you're tempted to put extra shenanigans at
the end of the constructor itself: any constructor that calls a method
that is non-static, non-final (or non-private) may provide you with some
odd-seeming surprises later.
To demonstrate:
Q: What does the code below output to the screen? (Please don't compile
and run this - just answer by reading the code.)
class A {
public A() {
setUpSomeThings();
}
protected void setUpSomeThings() {
// some setup code in here
}
}
public class B extends A {
private int memberVariable = 0;
public B() {
super();
System.out.println("memberVariable = "
+ memberVariable);
}
protected void setUpSomeThings() {
memberVariable = 7;
}
public static void main(String[] args) {
B bInstance = new B();
}
}
Bonus question: What is the output if we change the line:
private int memberVariable = 0;
For reasons demonstrated by the code above, constructors should be kept
as simple as possible. Constructors that have a side effect (such as
showing a window, or generally performing any action (a verb!) in any
higher level sense) are to be avoided.
A constructor generally constructs (sets up) a *thing* (an object - or
think 'noun') -- and any actions (verbs) that that thing will do should
usually be triggered by calling a method on that object.
Perhaps using a factory... but I would
like not to touch the existing code regarding the creation of the
ins
A factory may help - but again, what is the situation you're dealing
with here?
lex