If you don't use Java Generics, I believe it's not possible to have two methods in the same class that differ only in their return type.
In other words, this would be illegal:
public HappyEmotion foo(T emotion) {
// do something
}
public SadEmotion foo(T emotion) {
// do something else
}
Is the same true when overloading methods that return a generic type that may implement different interfaces, such as if the following two methods were present in the same class definition:
public <T extends Happy> T foo(T emotion) {
// do something
}
public <T extends Sad> T foo(T emotion) {
// do something else
}
Would this be illegal?
Method overloading. In a class, there can be several methods with the same name. However they must have a different signature. The signature of a method is comprised of its name, its parameter types and the order of its parameters.
Method overloading cannot be done by changing the return type of methods. The most important rule of method overloading is that two overloaded methods must have different parameters.
A generic method can also be overloaded by nongeneric methods. When the compiler encounters a method call, it searches for the method declaration that best matches the method name and the argument types specified in the call—an error occurs if two or more overloaded methods both could be considered best ...
Changing the Data Type of ParametersAnother way to do method overloading is by changing the data types of method parameters. The below example shows how we can implement method overloading with the different data types of parameters in method declaration and definition.
This is legal since the input parameter too differs based on the type..
For this reason, following is legal,
public <T extends Happy> T foo(T emotion) {
// do something
}
public <T extends Sad> T foo(T emotion) {
// do something else
}
But following is not,
public <T extends Happy> String foo(T emotion) {
// do something
}
public <T extends Happy> T foo(T emotion) {
// do something else
}
Thanks...
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