Cheers Munees
My Blog
Harpreet Singh janda wrote:Hi Sachin,
As there is not exact match for a method printObj with a parameter "GrandSon". So the compiler will check for any other method which can be used in a polymorphic way, means any overloaded version which can be used by passing "GrandSon" object. Candidate methods are those which accepts the parent class of "GrandSon". In your code there are three such methods :
All of these three methods can be called by passing "GrandSon" as an argument. So compiler will be confuse because of multiple eligible methods and will not be able to conclude any single method to call, Hence throws an exception regarding ambiguous methods.
class Dad {
String printMe() {
System.out.println("Dad");
return "Dad";
}
}
public class Son extends Dad {
String printMe() {
System.out.println("Son");
return "Son";
}
public static void main(String[] args) {
GrandSon o = new GrandSon();
o.printObj(o);
}
}
interface Intfc {
String printMe();
}
class GrandSon extends Son implements Intfc {
public String printMe() {
System.out.println("GrandSon");
return "GrandSon";
}
void printObj(Son o) {
System.out.println("1 " + o.printMe());
}
void printObj(Dad o) {
System.out.println("2 " + o.printMe());
}
void printObj(Intfc o) {
System.out.println("3 " + o.printMe());
}
}
Thanks & Regards
Sumit Kothalikar
Simran Dass wrote:
Hi ,
THis is bec the compiler looks for the most specific method. Among printObj(Son)
and printObj(Dad) method printObj(Son) is the most specific one. So the compiler gives
no error. But when you also have printObj(intrf) together with these two methods compiler
cannot find the most specific method and hence the error.
Simran Dass wrote:
One which is closest in the inheritance hierarchy. Grandson extends Son , Son extends Dad.
So printObj(Son) is the closest one.
Sachin Deokar wrote:
Prabhat Shankar Consumer Court,Consumer Court India,Consumer Complaints,Complaint India, Web Value
Jesper Young wrote:
It's better to use class names that reflect the "is a" relationship. For example, make a class Animal, and a class Cat that extends Animal. A Cat is an Animal.
My previous laptop never exploded like that. Read this tiny ad while I sweep up the shards.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
|