Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forced Downcasting in Java

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){
  ..
like image 677
Meindert Avatar asked Nov 29 '25 08:11

Meindert


1 Answers

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.

like image 77
Mark Peters Avatar answered Nov 30 '25 21:11

Mark Peters