Decison between overriding methods & arithmetic prmotable overloaded methods
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
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
posted
0
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://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.
subject: Decison between overriding methods & arithmetic prmotable overloaded methods