+ 1

This code is an example of multiple inheritance but java does not support this how is this an ex of polymorphism

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"); } }

28th Jul 2017, 5:05 PM
Jayashri Thandapani
Jayashri Thandapani - avatar
2 odpowiedzi
+ 2
This isn't multiple Inheritiance. Polymorphism can occur because of this: public class Program{ public static void main(String[] a){ Animal obj = new Cat(); } } Here i've assigned an Animal the value of a Cat. Quote from tutorials point: "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 reference is used to refer to a child class object." The way you've structured your hierarchy makes an Animal be able to take the value of an Animal, Dog or Cat. Think of it as: An animal is a cat. An Animal is a dog. So the following is valid: Animal ct = new Cat(); Animal dg = new Dog(); Play around with that to see the effect it has on the object (what method you can access due to the type of object it is)
28th Jul 2017, 5:52 PM
Rrestoring faith
Rrestoring faith - avatar
+ 2
A programming language that supports multiple inheritance allows a child class to inherit from two or more base classes. In your example, two child classes (Cat and Dog) inherit from one base class (Animal). This is single inheritance and perfectly legal in Java. It's an example of polymorphism (one name, many forms) because you can do the following in main method: Animal a = new Cat(); a.makeSound(); ⏩output Meow a = New Dog(); a.makeSound(); ⏩output Woof Although variable a is of type Animal, the object it references can be of type Animal or any subclass of Animal. The correct implementation of makeSound() is defined by type of the referenced object and executed at runtime.
28th Jul 2017, 5:54 PM
Jan Moriaux
Jan Moriaux - avatar