Assume that Animal is a class that has method void info() that prints "I am an animal". Classes Bird and Mammal both extend class Animal, and both override method info(). Class Bird implements method info to print "I am a bird", and class Mammal implements method info to print "I am a mammal". Determine the outcome printed by the following lines of code.
Animal animal = new Mammal();
animal.info(); //OUTCOME:
animal = new Animal()
animal.info(); //OUTCOME:
animal = new Bird();
animal.info(); //OUTCOME:
Java supports runtime polymorphism also known as dynamic polymorphism. Call to an overridden method is resolved at runtime rather than at compile-time. As per this, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
Animal animal = new Mammal();
animal.info(); //OUTCOME: "I am a mammal"
animal = new Animal()
animal.info(); //OUTCOME: "I am an animal"
animal = new Bird();
animal.info(); //OUTCOME: "I am a bird"
Get Answers For Free
Most questions answered within 1 hours.