2

I'm learning programming in java using generic types and got a probably very basic question.

Where's the difference between the further two snippets?

1.)

public void build(House house) {
    // work only with house objects that extending House
}

2.)

public <T extends House> void build(T house) {
    // work only with house objects that extending House
}
0

3 Answers 3

5

There is no difference between these two methods with respect to what they can take in as parameters; however, in the latter example, one does have access to the specific type T. Regardless, this example does not illustrate the power of generics.

As an example consider a LinkedList of Node<T> objects. We can define a wrapper, Node<T>, which can hold an object of any type. This is a very useful construct, as it allows us to write one piece of code that can be used for many different objects.

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

Comments

1

The difference is that inside the second function you have access to type type T, the type the caller used to access your method.

I can't think however of any way to use that type that would differ meaningfully from using House directly. It might make a difference with some other parameters or return types of the method.

Comments

0

They are logically the same.

Although, on the second case the compiler can make some advanced verifications.

Let´s say there is are two subclasses of House called XHouse and YHouse.

We have the following source code:

XHouse house = build(yHouse)

This will fail if yHouse is an object of type YHouse and YHouse is not a subclass of XHouse.

Think of a generic as a sort of template. When you fill the generic argument, you sort of create a new method. In the example above, the usage of the generic method is virtually creating the following:

public XHouse void build(XHouse house) {
    // work only with XHouse objects that extending XHouse
}

Notice I even changed the comments.

2 Comments

Your example is good, but it requires that the return type is changed from void to T.
Yes, it does. But the author of the question amended that. The question needs editing. Which I just did.

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.