I have a method
public int addTransaction(Transactions tr){
//etc...
}
and now I want to create a new method, which will do exactly like addTransaction but it will take a different type object Order order.
I realise that I can create this:
public int addTransaction(Order tr){
//etc...
}
However I was wondering if I can have one method with generic type inside the parenthesis so to pass whatever object I want. Can this be done?
Can you pass any object using generics? Yes. You do it like this:
public <T> int addTransaction(T tr) {
// ...
}
The question is, though, what does that do for you? That incantation is equivalent to
public int addTransaction(Object tr) {
// ...
}
since the T is unconstrained. Either way, all you can really do with tr is invoke methods declared/defined on Object.
Now, if there is some common parent type that Transaction and Order (and anyone else) share, then things start to make a little more sense. If the common parent type is Parent, then you can write something like
public <T extends Parent> int addTransaction(T tr) {
// ...
}
and you can now treat tr as in instance of Parent. But what does that give you over the following?
public int addTransaction(Parent tr) {
// ...
}
Nothing that I can see.
So, bottom line, yes you can do such a thing, but the value of doing it is suspect.
Generic methods are created as follows
public <T> int addTransaction(T tr){
//TODO:
return 0;
}
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