Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you do method overloading with generics and only change the generic type of the method signature?

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?

like image 995
Brendan Downes Avatar asked Aug 29 '11 03:08

Brendan Downes


People also ask

Does method overloading require same type signature?

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.

Can we achieve method overloading by changing the return type of method only?

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.

Can generic methods be overloaded?

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 ...

Can we change data type in method overloading?

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.


1 Answers

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...

like image 53
Prabath Siriwardena Avatar answered Nov 13 '22 01:11

Prabath Siriwardena