0

If i have this:

class MyClass {
    double calcAverage(double marks1, int marks2) {
        return (marks1 + marks2)/2.0;
    }
    double calcAverage(int marks1, double marks2) {
        return (marks1 + marks2)/2.0;
    }
    public static void main(String args[]) {
        MyClass myClass = new MyClass();
        myClass.calcAverage(2, 3);
    }
}

Compiler can't determinate which overloaded method "calcAverage" should be called. I understand this. So I was exploring some examples to see if I understand fully this idea. I came to this example and I am confused:

public class MyClass {
 double metoda(int marks1, double marks2){
    System.out.println("int + double");
    return (marks1 + marks2)/2.;
}

double metoda(char marks1, double marks2){
    System.out.println("char + double");
    return (marks1 + marks2)/2.;
}

double metoda(char marks1, int marks2){
    System.out.println("char + int");
    return (marks1 + marks2)/2.;
}

public static void main(String args[]) {
    MyClass ss = new MyClass();
    char a = 2;
    char b = 3;
    double var = ss.metoda(a, b);
}
}

All 3 of this methods can accept "char, char" arguments, but still, there is NO compilation error. If I run this program, metoda(char .., int..) is executed. If i delete this method and execute program again, then metoda(char .., double..) is called. I don't understand why this is not compilation error and how does compiler knows which method to call.

mislav23
  • 83
  • 5
  • It will always pick the third method because it can cast a char into an int, but it would need to cast again from int to double for either of the other methods. – Andreas Hartmann Feb 14 '18 at 09:55
  • Each character has it's own value, see https://en.wikipedia.org/wiki/ASCII – Thum Choon Tat Feb 14 '18 at 09:55
  • try this to indicate to the compiler which method you wish to call : myClass.calcAverage(2, 3.0); or myClass.calcAverage(2.0, 3); – akshaya pandey Feb 14 '18 at 09:58
  • @AndreasHartmann i didn't know double cast is needed for char -> double. So if i got it correctly, compiler is taking method that needed as less as possible cast. So if i have two methods with same number of cast then it will be compiler error? – mislav23 Feb 14 '18 at 10:06
  • https://stackoverflow.com/questions/1572322/overloaded-method-selection-based-on-the-parameters-real-type Take a look at best answers here (accepted and that with most upvotes), they can help you understand it as it's well explained there. – Przemysław Moskal Feb 14 '18 at 10:18

0 Answers0