My teacher has posted this and i dont quite get what is polymorphism and especia
ID: 3772851 • Letter: M
Question
My teacher has posted this and i dont quite get what is polymorphism and especially why this example is a good example of polymorphism
______________________________________________________________________________________________________________
Explain why the following example is an excellent example of polymorphism.
public class AnimalReference
{
public static void main(String args[])
Animal ref; // set up var for an Animal; this is superclass
Cow aCow = new Cow("Bossy"); // makes specific objects
Dog aDog = new Dog("Rover");
Snake aSnake = new Snake("Ernie");
// now reference each as an Animal
ref = aCow; ref.speak();
ref = aDog; ref.speak();
ref = aSnake; ref.speak();
}
Explanation / Answer
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class or super class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic.The three types of polymorphism are: ad-hoc (overloading and overriding), parametric (generic typing) and dynamic method binding.
Example:
public class AnimalReference
{
public static void main(String args[])
Animal ref; // set up var for an Animal; this is superclass
Cow aCow = new Cow("Bossy"); // makes specific objects
Dog aDog = new Dog("Rover");
Snake aSnake = new Snake("Ernie");
// now reference each as an Animal
ref = aCow; ref.speak();
ref = aDog; ref.speak();
ref = aSnake; ref.speak();
}
Here AnimalReference class is polymorphic since it have Animal kind of reference variable which can be cow, dog or snake, each having their own speak() method.
Here subclasses (Cow, Dog and Snake) have been created based on the Animal abstract class, each having their own speak() method. Although each method reference is to an Animal (but no animal objects exist), thus the program will resolve the correct method reference at runtime.
This is thired type of polymorphism that is Dynamic (or late) method binding.
Dynamic (or late) method binding is the ability of a program to resolve references to subclass methods at runtime.
so the given example is an excellent example of polymorphism.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.