File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Why i need Class Generics? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why i need Class Generics?" Watch "Why i need Class Generics?" New topic

Why i need Class Generics?

sriram sundararajan
Ranch Hand

Joined: Apr 08, 2003
Posts: 43
Hi All,
I understand the need of Generics in Collections. We can avoid runtime error and in the compilation time itself we can identify the exceptions and resolve it.

My doubt is why i need class level Generics? Look at the following code snippet, and advice me what kind of benefit i am getting from making the class b as generics.

Rob Spoor

Joined: Oct 27, 2005
Posts: 20188

You don't. Adding generics should add benefits like no longer having to make casts, or having the risk of ClassCastExceptions.

How To Ask Questions How To Answer Questions
sriram sundararajan
Ranch Hand

Joined: Apr 08, 2003
Posts: 43
Yes, i got it. But in the above example, how it make sense?
Paul Clapham

Joined: Oct 14, 2005
Posts: 19864

sriram sundararajan wrote:But in the above example, how it make sense?

It doesn't. If the person who gave you the code claims that the use of generics provides some benefit, you should ask them why they think that.
sriram sundararajan
Ranch Hand

Joined: Apr 08, 2003
Posts: 43
I am learning generics, i only wrote this code for my understanding.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3028
A generic class can provide benefits, sure. If there's some larger purpose being served. But if you just throw generics into a class, without any planned purpose, it's unlikely you will be able to do anything useful with them. Much like you can't create a sentence in English by simply choosing random words from an English dictionary.

If you want to see what benefits a generic class can provide, I suggest looking at List, and/or ArrayList. If someone gives me a List, how do I know what's in it? Should I just assume that the things inside are, let's say, Strings? Then cast to String and see if we get an exception. Or maybe check first using "if (element instanceof String)". Blech. Much better to get a List<String> in the first place, so you know that the things in the list are Strings. And the compiler knows. And we don't have to guess.
I agree. Here's the link:
subject: Why i need Class Generics?
It's not a secret anymore!