Search code examples
javainterfaceabstractabstraction

Using abstraction and interface on the same Object without having to cast it


I would like to use abstraction(from a mother class) and an interface on the same Object without having to cast it.

I've already search about it and it seems that casting is a common method for that kind of purpose.

I have got a program where Dog extends Animal implements Friendly

Animal let the dog yell() and Friendly (Interface) let him hug() Before using Friendly(Interface), I used to do it :

Animal dog = new Dog();
dog.yell();

but now, to add the interface, I have to cast the dog into a Friendly type like that so that he can hug() :

Animal dog = new Dog();
dog.yell();
((Friendly) dog).hug();

Is there any better way to do this as my teacher told me that casting was usually a bad idea.


Solution

  • If you need to avoid casting, then you have to use Dog as the type of your dog variable:

    Dog dog = new Dog();
    dog.yell();
    dog.hug();
    

    With this, though, you aren't programming to the Friendly and Animal interfaces, which you should ideally do when abstraction is used correctly. If you must declare dog as Animal or as Friendly in code just like this, then you're using abstraction for the wrong reasons.

    ...my teacher told me that casting was usually a bad idea.

    Casting is something no one likes doing, but everyone has to do it when it's necessary.