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
}
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.
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.
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.
If i change the
byte
toint
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With