| Author |
creating restricted object type to Generic classes
|
Tanu Gulati
Ranch Hand
Joined: Oct 06, 2008
Posts: 113
|
|
Hi, i wanted to create a class which only be created of type Integer so i put <Integer> after Test. but on compiling this class i am getting error "can not make a static reference to a non static type Integer" ISit not the correct way to create an object of the class which takes only Integer?.if it is not then how? My Second Question is -- Is it possible to create a class using Generics whose objects can be only of two types say "Integer" and "String". May be this is very silly question to put ..but i am just trying to understand Generics better. [ November 24, 2008: Message edited by: Tanu Gulati ]
|
thanks
Tanu Gulati
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Originally posted by Tanu Gulati: Hi, i wanted to create a class which only be created of type Integer so i put <Integer> after Test. but on compiling this class i am getting error "can not make a static reference to a non static type Integer" ISit not the correct way to create an object of the class which takes only Integer?.if it is not then how?
If the class's "generics" are only limited to Integer, then why use generics at all?? It's like Henry Ford's famous quote:
Any customer can have a car painted any colour that he wants so long as it is black.
If you still need this though, you can make use of the fact that Integer is final: There is only one class for which this will match: Integer.
My Second Question is -- Is it possible to create a class using Generics whose objects can be only of two types say "Integer" and "String".
Unfortunately, it is not. You can specify AND using & OR is not possible as far as I know. [ November 24, 2008: Message edited by: Rob Prime ]
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Tanu Gulati
Ranch Hand
Joined: Oct 06, 2008
Posts: 113
|
|
|
mmmm...i started understanding Generics ....a big thanks to you Rob
|
 |
 |
|
|
subject: creating restricted object type to Generic classes
|
|
|