Java polymorphism | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita

Java polymorphism

having class Animal and a Animal subclass Cat, what is the difference between declaring Animal a = new Cat() and Cat a = new Cat()?

30th Dec 2016, 1:15 PM
samy jaimes
samy jaimes - avatar
2 Respuestas
+ 1
1. a is Animal and you can not use Cat methods using a.catMethod(...). But it is possible to use ((Cat)a).catMethod(...). 2. a is Cat and you can use Cat methods.
30th Dec 2016, 1:23 PM
Daniil Fomichev
When using Animal a = new Cat(); a is of type Animal and you can only use public methods and public variables that class Animal has. With Cat c = new Cat(); c is a type of Cat and you can use public methods + variables of Animal + Cat.
30th Dec 2016, 1:20 PM