wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Decison between overriding methods & arithmetic prmotable overloaded methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Decison between overriding methods & arithmetic prmotable overloaded methods" Watch "Decison between overriding methods & arithmetic prmotable overloaded methods" New topic
Author

Decison between overriding methods & arithmetic prmotable overloaded methods

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi ,
How does the javac decide which method to run when there is
a combo of overriding methods and overloaded methods with the
latter being able to be called using prmotion.
1. Case 1 : following code gives compiler error - ambiguous method1
class A{
public void method1(byte b) {
System.out.println("Called Method in Class A");
}
}
class B extends A {
public void method1 (int i){
System.out.println("Called Method in Class B");
}
}
public class OverloadPromotion extends B {
public static void main(String[] args) {
byte b = 10;
OverloadPromotion c = new OverloadPromotion();
c.method1(b);
}
Case 2 : As expected, Compiles and calls 'method in b'.
class A{
public void method1(int i) {
System.out.println("Called Method in Class A");
}
}
class B extends A {
public void method1 (byte b){
System.out.println("Called Method in Class B");
}
}
public class OverloadPromotion extends B {
public static void main(String[] args) {
byte b = 10;
OverloadPromotion c = new OverloadPromotion();
c.method1(b);
}
Why is the case 1 throwing error when compiler can call
the method in class b. I thought the methods are chosen
by searching up the class heirarchy. As soon as it finds the
method in class b, it can promote byte into int and then execute.
Can some one explain this...
Regards
Sreddy
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Good question.
Now if you carefully note when you pass a byte it can be promoted both as an int and it can be accomodated within a byte, hence the compiler is unable to identify which method to call.
Whereas in the second case the compiler identifies the first matching parameter and this is taken as the method to be executed.
Hope this helps.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Decison between overriding methods & arithmetic prmotable overloaded methods