This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why i need Class Generics?" Watch "Why i need Class Generics?" New topic
Author

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
Sheriff

Joined: Oct 27, 2005
Posts: 19656
    
  18

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
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
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

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: 3003
    
    9
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.
 
 
subject: Why i need Class Generics?
 
Similar Threads
Generics
Generics
Generics
Generics..
Generics Question.