Snake
Snake

Reputation: 14648

Access same variable in subclass and parent class using different scope

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?

Upvotes: 3

Views: 300

Answers (1)

Joni
Joni

Reputation: 111239

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.

Upvotes: 3

Related Questions