0

classe animal has makesound function i.e grr..... nd classes cat and dog also have makesound function i.e meow nd woof respectively... due to inheritance classes cat and dog also have makesound function of animal class ie grr.... now my q is how compiler will know which function to execute is nt ds ambiguous??... two choices r dere.... 1 make sound function of animal class ie grr 2 make sound function of own like woof or meow.... any help would be really helpful....

21st Aug 2016, 5:08 AM
Amandeep Singh
Amandeep Singh - avatar
6 Respostas
+ 2
ya... i have also heard of ds...ds is correct.... but why r we or how can we using animal object to point to cat and dog....like below animal a=new cat(); animal b=new dog(); how ds helping us to achieve polymorphism... nd can we use parent class object to point to child class object.... how is ds possible.... @James
21st Aug 2016, 9:16 AM
Amandeep Singh
Amandeep Singh - avatar
+ 1
It is only ambiguous in multiple inheritance, which is basically not possible in Java unless using interfaces. If a child class has the exact same method name as it's parent class, but different body of course, the child class has overridden its parent classes method. The compiler is designed to check for this. If a method is overridden, that method will be called. If you wanted a child class to call it's parent class method, you can use the super(); keyword in the first line of the child class method.
21st Aug 2016, 9:07 AM
James
James - avatar
0
Through casting..see below Ex: class Car { public String getCompany(){ return null; } } class Corola extends Car { public String getCompany(){ return "Toyota"; } } class City extends Car { public String getCompany(){ return "Honda"; } } class Test { public static void main (String[] args){ Car c1 = new Corola (); Car c2 = new City (); show (c1); //Toyota show (c2); //Honda } // show method accepts all classes that extend Car public static void show (Car car){ System.out.println (car.getCompany ()); } }
21st Aug 2016, 7:53 AM
Tiger
Tiger - avatar
0
not ryt....actually how casting can resolve ambiguity....ds is d same program as in example animal cat dog... difference is only you use extra show function... nd ur passing c1 object of tyoe car to show function... i know output is coming but how compiler resolves dat ambiguity is d question.... @Tiger
21st Aug 2016, 8:41 AM
Amandeep Singh
Amandeep Singh - avatar
0
Here, instead of writing it out, read everything in this link. It explains it very thoroughly. And btw, those aren't animal objects, theyre cat and dog objects referencing the animal class. http://www.cs.utexas.edu/~cannata/cs345/Class%20Notes/14%20Java%20Upcasting%20Downcasting.htm
21st Aug 2016, 9:24 AM
James
James - avatar
0
It's simply called method overriding
22nd Oct 2016, 3:04 PM
aditya v
aditya v - avatar