I have a question about something that maybe not be possible, but it is worth a try.
I have these classes:
Class A {
private int x = 0;
public A() {
afterCreate();
}
public void afterCreate() {
x = 10;
}
public int getX() {
return x;
}
}
Class B extends A {
public B() {
super();
//Do something
afterCreate();
}
@Override
public void afterCreate() {
x = 20;
}
}
Class C extends B {
public C() {
super();
//Do something
afterCreate();
}
@Override
public void afterCreate() {
x = 30;
}
}
As you can see, I need to ALWAYS, automatically call afterCreate()
when the constructor ends. But if I just call afterCreate()
inside each constuctor, you can see that for an object created from the class C
, we will call the method afterCreate()
three times (one for each constructor) -- the first two calls being useless.
Also, I can't call afterCreate()
just in the first constructor, because afterCreate()
MUST be executed after the last constructor.
Class A {
public A() {
//Do something
afterCreate();
}
}
Class B extends A {
public B() {
super();
//Doing something that I missed to process in afterCreate()!
}
}
Class C extends B {
public C() {
super();
//Doing something that I missed to process in afterCreate()!
}
}
Obviously, I can't call afterCreate()
in the constructor of the class C, because if I create objects from class A or B, the method would not be called.
Is there a way to ALWAYS, automatically call afterCreate()
when the LAST constructor ends?
Right now, thinking about the problem, maybe if I can detect that the constructor is called in a super class, I could detect whether I can call the method.
Class A {
public A() {
//Do something
if(thisIsNotCalledAsASuperClass()) afterCreate();
}
}
Class B extends A {
public B() {
super();
//Do something
if(thisIsNotCalledAsASuperClass()) afterCreate();
}
}
Class C extends B {
public C() {
super();
//Do something
if(thisIsNotCalledAsASuperClass()) afterCreate();
}
}
//Class D extends C {
//etc.
I don't know.... What do you think?