Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Decison between overriding methods & arithmetic prmotable overloaded methods

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic