Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a method in JAVA with generic object parameter

Tags:

java

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?

like image 859
yaylitzis Avatar asked Oct 25 '25 01:10

yaylitzis


2 Answers

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.

like image 161
Erick G. Hagstrom Avatar answered Oct 27 '25 14:10

Erick G. Hagstrom


Generic methods are created as follows

public <T> int addTransaction(T tr){
    //TODO:
    return 0;
}
like image 29
Alpesh Valia Avatar answered Oct 27 '25 15:10

Alpesh Valia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!