4

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?

1
  • Can we do: public class SOTest<T> {public int addTransaction(T tr){}} Commented Jul 1, 2016 at 12:41

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Generic methods are created as follows

public <T> int addTransaction(T tr){
    //TODO:
    return 0;
}

2 Comments

The use of generics here is unnecessary: you might as well simply use Object.
That could be also used!
1

Unless there is a superclass/subclass relationship between Order and Transactions, no. And if there is such a relationship, you simply need the overload which takes the superclass.

Comments

0

Transaction and Order will need to both extend from the same Class or implement the same Interface, or one will need to extend the other in order for this to work.

Here are a couple of examples:

One Class extending the other:

public class Test {

    public int addTransaction (final Transaction tr) {

    }
}

class Transaction {

}

class Order extends Transaction {

}

Both sharing a common Interface:

public class Test {

    public int addTransaction (final Process tr) {

    }
}

interface Process {

}

class Transaction implements Process {

}

class Order implements Process {

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.