Blizzer
Blizzer

Reputation: 260

Java generics basics

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
}

Upvotes: 2

Views: 126

Answers (3)

Akira
Akira

Reputation: 4071

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.

Upvotes: 0

Steve P.
Steve P.

Reputation: 14709

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.

Upvotes: 5

Flavio
Flavio

Reputation: 11977

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.

Upvotes: 1

Related Questions