Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a compilation error when I try to have two methods with the same name and parameter type?

Tags:

java

If i change the byte to int I get a compiler error. Could you explain the problem?

public class A {
   protected int xy(int x) { return 0; }
}

class B extends A {
   protected long xy(int x) { return 0; } //this gives compilor error
   //protected long xy(byte x) { return 0; } // this works fine
}   
like image 466
jai Avatar asked Apr 03 '14 12:04

jai


People also ask

What happened if two methods have same name same parameters but different return type?

The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return types. It will throw a compile-time error. If both methods have the same parameter types, but different return types, then it is not possible.

Can you have two methods with the same name?

Two or more methods can have the same name inside the same class if they accept different arguments. This feature is known as method overloading. Method overloading is achieved by either: changing the number of arguments.

Can a function with same name have different return types?

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.


1 Answers

If i change the byte to int I get a compiler error.

If you do that, you have this:

public class A {
   protected int xy(int x) { return 0; }
}

class B extends A {
   protected long xy(int x) { return 0; }
}   

...and the only difference in the xy methods is their return type. Methods cannot be differentiated solely by their return types, that's the way Java is defined. Consider this:

myInstance.xy(1);

Which xy should that call? long xy(int x) or int xy(int x)?

If your goal is to override xy in B, then you need to make its return type int in order to match A#xy.

like image 154
T.J. Crowder Avatar answered Nov 15 '22 02:11

T.J. Crowder