everyone, this may sound a bit weird, but I want to set the value of a super class variable and set it equal to something that will be in the subclass. For example, I have an abstract class called SpriteBody
, and in a method called def
, I want to set the variable bodyType
to something that is defined within Block
which extends SpriteBody
how can I do something like this?
I could do this the other way around, setting the value of a super class, and using the variable in the super class's method, but I could write less code if I could do it the first way.
The abstract superclass can declare an abstract method for the subclass to implement. For example:
public abstract class SpriteBody {
private BodyType bodyType;
protected abstract BodyType determineBodyType();
public void def() {
bodyType = computeBodyType();
}
}
public class Block extends SpriteBody {
@Override
protected BodyType determineBodyType() {
// ... TODO ...
}
}
That said, inheritance is a bit of a minefield, and this sort of approach can lead to complicated coupling between the base class and the child classes, that can make it very hard to make sure that all child classes are behaving correctly and preserving the right invariants. So while the above is perfectly valid, it might be worth taking a second look to see if you can accomplish your goals using composition rather than inheritance.