3

I often run into this and cant find elegent way to do this this. Lets say I have class A being the parent class and class B being the subclass

class A {
    protected Animal anim;
    public A(){
    }

}

class B extends A{
    public B(){
       anim = new Dog();
    }

    private doSomething(){
       ((Dog)anim).accessDogMethod();
    }
}

My problem is always with the variable anim. I want to access specific Dog methods. However I can't do it unless I downcast it. I don't want to downcast it everywhere. So the only way I found was:

class B extends A{
    private Dog dog;
    public B(){
       anim = new Dog();
       dog = anim; 
    }

    private doSomething(){
       dog.accessDogMethod();
    }
}

However there has to be nicer way. I want the variable in both parent class and subclass so each class access their relevent info

Any suggestion?

2
  • 1
    So you have two parallel class hierarchies: B -> A and Dog -> Animal. Maybe you can avoid this by modifying the design somehow. Commented Feb 28, 2016 at 13:10
  • I think you should declare super method on Animal, then implement on sub class. Commented Feb 28, 2016 at 13:10

1 Answer 1

3

You could use parametric types (i.e. generics).

class A<T extends Animal> {
    protected T anim;
    public A(){
    }
}

class B extends A<Dog> {
    public B(){
       anim = new Dog();
    }

    private doSomething(){
       anim.accessDogMethod();
    }
}

It sounds like you have parallel inheritance hierarchies. That is a common code smell that indicates that you may want to rethink your design.

Sign up to request clarification or add additional context in comments.

3 Comments

Will this suggested solution let me access the method accessDogMethod which is only available for Dog object?. Yes I have a parallel inheritance hierarchies. Is this bad or frown upon?
Yes it will. When you have parallel hierarchies it means that when something has to change you have to make the change in two different places. It also means you have to keep two things in your head instead of one while you work on the program, and typically a person can keep track of 7 items at any particular time, so you are more likely to make a mistake. But sometimes these hierarchies are a necessary evil and the alternatives would be even worse.
Ah ok thank you for the explanation and the suggested answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.