Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Generics in Java Generics in Java Generic Functions

Tian Yu
Tian Yu
611 Points

what is the purpose of adding a type parameter to a method? Any example like the one for the classes?

like for the type parameter of a class, you can define a box object for specific T type object, is there a similiar usage for Type parameter in methods? How?

1 Answer

We used the Type parameter in a Method in this lesson. Why?

For the same reason you add a Type parameter to a Class - it makes for more readable code & lets your IDE help you find errors before compile-time.

We did this in the prior lesson when we defined the Box class. The Box class was written so when it is called it needs to have its Type defined, which we did. When we later used that specific Box declaration to add to the Box the IDE checked to ensure whatever we added matched the Type we declared previously. If not the IDE shows an error. The IDE makes that error a lot easier to correct than a compile-time error message.

By adding Types to Methods we're doing this exact same thing, but doing it dynamically rather than individually declaring each Box declaration. Even though in this lesson we did manually declare "debugAdd" for Milk and Oranges there's no reason this could not have been done dynamically in a bigger project. This ensures every time we use this Method that it's done PRECISELY the way the Method is built for.

This way our Method only runs with a Type declaration, the Type needs to be passed to the method when its called, and the Type is assigned to the Box that is created.

Thus in the future, if we ever do anything with a specific Box - whether it's the Milk or Oranges - that Milk Box or Orange Box can only handle specifically the things it is allowed to handle. If you try to send something to the MIlk Box that it cannot handle the IDE can help you by pointing out your mistake. Even if you do not have an IDE the nature of Generics & Type declarations makes it easier to go back and manually review your code to find the mistake.

All of this adds security to your code as well as it prevents a theoretical Box from having the wrong things placed in it, which prevents exploits you may not see at first glance in a more complicated codebase.