Search code examples
javaoverloading

Doing all possible int + double combination in method overloading


So our teacher gave us this method overloading example

//getting perimeter of Triangle

public int getPerimeter(int a, int b, int c){
    return a + b + c;
}
public double getPerimeter(double a, int b, int c){
    return a + b + c;
}
public double getPerimeter(int a, double b, int c){
    return a + b + c;
}
public double getPerimeter(int a, int b, double c){
    return a + b + c;
}
public double getPerimeter(double a, double b, int c){
    return a + b + c;
}
public double getPerimeter(int a, double b, double c){
    return a + b + c;
}
public double getPerimeter(double a, int b, double c){
    return a + b + c;
}
public double getPerimeter(double a, double b, double c){
    return a + b + c;
}

In my opinion, isn't the first and last method enough? I think the methods between the first and last are redundant overloading because a mix of ints and doubles would be accepted by the one with an all double parameter.

Can anyone enlighten what's the purpose of coding it this way?


Solution

  • Keep in mind, school will often try to teach concepts and often values the codes ability to illustrate those concepts over its practicality.

    With that in mind, you are correct in your assertion that you're unlikely overload like this in the real world; however, it's also worth noting that in the real world, you probably wouldn't write a dedicated method whose sole purpose is to add 3 numbers together either.

    One thing I think this exercise does well is helps articulate the practical limitations of overloading. For example, imagine having to support every combination of 10 different types across 10 different arguments.