+ 1

Why is the code printing "food" and not "dog food". Please explain.

I am learning java and while understanding polymorphism, I tried to use the string objects to understand how they work in polymorphism. However I got an unexpected output "food" instead of "dog food" that I expected. Please explain. https://code.sololearn.com/cJ5v2HXtTZbE/?ref=app

6th Dec 2021, 7:38 PM
Ruchika Sehgal
Ruchika Sehgal - avatar
3 Respostas
+ 2
You declared c as "Animal c = new Cat();", so it uses the variable food class Animal. You need to use: Cat c = new Cat();
6th Dec 2021, 8:16 PM
Solo
Solo - avatar
0
In Inheritance, parent class reference variable always points to subclass methods when it is up casted or assigned child class object. But not data fields or member variables are overridden, it still points to it's local instance data fields of parent class. Data fields are always first searched in local variables area, if there not found then it's search in parent class variables list. if still not found then it's produse error of undefined. c is parent class reference variable. and c.food points to "food" of parent class. polymorphism can't be achieved by data fileds. hope it helps..
6th Dec 2021, 8:12 PM
Jayakrishna 🇮🇳
0
The good thing about extends is that you don't need to rewrite the same thing: class Animal { protected String food = "Food"; protected String sound = "Grr..."; public void makeSound(){ System.out.println(sound); } } class Cat extends Animal { Cat(){ food = "Cat food"; sound = "Meow"; } } class Dog extends Animal { Dog(){ food = "Dog food"; sound = "Woof"; } } class Program { public static void main(String args[ ]) { Dog dog = new Dog(); Animal cat = new Cat(); dog.makeSound(); cat.makeSound(); System.out.println(cat.food); } }
6th Dec 2021, 9:27 PM
Solo
Solo - avatar