0

Help me detect my error

I was going through polymorphism in Java tutorials of Sololearn wherein I found this code snippet. class Animal { public void makeSound() { System.out.println("Grr..."); } } class Cat extends Animal { public void makeSound() { System.out.println("Meow"); } } class Dog extends Animal { public void makeSound() { System.out.println("Woof"); } } class Program { public static void main(String args[ ]) { Animal a = new Dog(); Animal b = new Cat(); a.makeSound(); b.makeSound(); } } the above one is the code snippet provided by the Sololearn. If i add object c for class Animal, the code snippet doesn't work and is showing error. Please help me out class Animal { public void makeSound() { System.out.println("Grr..."); } } class Cat extends Animal { public void makeSound() { System.out.println("Meow"); } } class Dog extends Animal { public void makeSound() { System.out.println("Woof"); } } class Program { public static void main(String args[ ]) { Animal a = new Dog(); Animal b = new Cat(); Animal c = new Animal(); a.makeSound(); b.makeSound(); c.makeSound(); } }

27th Jul 2017, 5:02 AM
Antoreep Jana
Antoreep Jana - avatar
7 Answers
+ 8
i copied and pasted the code. no edits. it works for me
27th Jul 2017, 6:17 AM
jay
jay - avatar
+ 7
odd. could you show this in codeplayground?
27th Jul 2017, 6:38 AM
jay
jay - avatar
+ 2
what error? line number?
27th Jul 2017, 5:09 AM
Venkatesh Pitta
Venkatesh Pitta - avatar
+ 2
The first code snippet gave output as Woof Meow which was as expected. But after adding the object c of class Animal and calling the makeSound() , it didn't work/ using the second code snippet, I wasn't getting any output whereas I expected output for second code snippet to be Woof Meow Grrr.... But the compiler showed some error to me. Help me out where is the fault in logic.
27th Jul 2017, 6:14 AM
Antoreep Jana
Antoreep Jana - avatar
+ 2
By adding Animal c = new Animal(); and c.makeSound(); to the first code snippet , i am receiving error.
27th Jul 2017, 6:36 AM
Antoreep Jana
Antoreep Jana - avatar
+ 1
It's fine....maybe there is a bug...If it's working fine in ur playground then it's fine. I just wanted to know whether I am committing any logical error or not. Thanks all of you for your kind concerns. :)
27th Jul 2017, 7:10 AM
Antoreep Jana
Antoreep Jana - avatar