Below are the instructions from Java Core Level 4, Lesson 3 Type casting. Widening and narrowing conversions My question is simple yet I can't establish an answer (that makes sense to me). Why would I need a type variable as a Cat and then assign it to a new object Tiger? It's a Tiger so should always be:-
Tiger tiger = new Tiger()
not
Cat cat = new Tiger();
Of course, I know there must be a good explanation😎
class Animal
{
public void doAnimalActions();
}class Cat extends Animal
{
public void doCatActions();
}class Tiger extends Cat
{
public void doTigerActions();
}
Here we have three class declarations: Animal, Cat, and Tiger. Cat inherits Animal. And Tiger inherits Cat. public static void main(String[] args)
{
Tiger tiger = new Tiger();
Cat cat = new Tiger();
Animal animal = new Tiger();
Object obj = new Tiger();
}
A Tiger object can always be assigned to a variable whose type is that of one of its ancestors. For the Tiger class, these are Cat, Animal, and Object.