I want to force a downcast on a object what can't be down casted and was wondering what the right approach would be.
The use case is that I have a list of rules that are checked and what will generate a list of failed rule. A failed rule is a subclass of a rule. But downcasting like
FailedRule failedRule = (FailedRule) rule;
will fail because the rule object is not an instanceof FailedRule
To work around this I instantiate a clone;
FailedRule failedRule = new FailedRule (rule);
and my FailedRule class looks like this
public class FailedRule extends Rule{
/*
*force a down cast from Rule to FailedRule through cloning
*/
public FailedRule (Rule upcast){
super.setRuleCode( upcast.getRuleCode());
super.setType(upcast.getType());
..
Is there a easier way to do this? To answer myself, the design is flawed, the code should be:
public class FailedRule{
private Rule rule;
..
public setRule(Rule rule){
..
This is probably a symptom that your inheritance hierarchy is weakly designed. You're trying to introduce mutability of attributes through inheritance (a Rule has "failed" if it is an instance-of FailedRule). Inheritance isn't really good for that sort of thing.
I would say you should either use composition (a FailedRule has a Rule as a source) or that failed should be a boolean attribute of an instance of Rule.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With