This is my first time using these forums, so I hope this thread is appropriate and that I don't mess up. This is in Java - I'll try and simplify the example to focus on the main problem. Any help would be appreciated!
Say I have two classes, Parent and Child, where Parent is an abstract class and Child extends Parent. (I'm writing this code on the fly)...
public abstract class Parent {
// A bunch of fields that have been omitted...
public Parent() {
print(getX());
}
public abstract int getX();
}
public class Child extends Parent {
private int x;
public Child(int x) {
super();
this.x = x;
}
@Override
public int getX() {
return x;
}
}
I want to instantiate Child, and call an abstract method immediately after instantiation. Obviously, currently there is an issue because the x field hasn't been set when getX() is called in the parent from super(), and therefore will always return 0.
However, I want this to be done in the parent for all children of Parent (if there is a Child2, Child3, etc. that extend Parent in the future). i.e. anything that extends Parent will have their "x" value printed. The work around to this would be to print getX() with every Child that is instantiated, but for some reason, it seems rather off to me to have to do this repeatedly inside every Child class, as opposed to having this captured in the Parent.
Any suggestions as to how I should approach this (calling an abstract method during instantiation)? Design pattern or design changes? Use the repeated call in the Child? Thanks :)