Anyone to explain this code for my better understanding? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Anyone to explain this code for my better understanding?

//here is the code class Animal { public void animalSound() { System.out.println("The animal makes a sound"); } } class Pig extends Animal { public void animalSound() { System.out.println("The pig says: wee wee"); } } class Dog extends Animal { public void animalSound() { System.out.println("The dog says: bow wow"); } } class MyMainClass { public static void main(String[] args) { Animal myAnimal = new Animal(); Animal myPig = new Pig(); Animal myDog = new Dog(); //please explain the code three rows before this comment! Why the words in front of the object for them are all Animal? Thank you. myAnimal.animalSound(); myPig.animalSound(); myDog.animalSound(); } }

16th Mar 2019, 11:20 AM
GO!
GO! - avatar
3 Answers
+ 1
Animal myPig = new Pig the word animal in front means that myPig inherits the animal class, then new Pig means that myPig also inherits the Pig class
14th May 2019, 6:31 PM
John Paul
John Paul - avatar
0
Are you referring to why it says new pig and new dog?
16th Mar 2019, 11:50 AM
Robert Atkins
Robert Atkins - avatar
0
That's the polymorphism in play. Since Pig and Dog extend Animal you can use the parent class (Animal as a type and then declare the object as its child)
16th Apr 2019, 2:55 PM
Zorry Serafimova
Zorry Serafimova - avatar