Generic class in a non generic class

N

nramnath

Hi,
I want to store a Generic class in a non generic class. Is it possible
??

public class A<T>
{
T t ;
public T getValue()
{
return t;
}
}

public class B
{
A a; // How to declare generic A here
public <T> A<T> getA()
{
return a;
}
}


I know this will not work. Is there a way I can get it working with
wildcards.
I am not 100% clear with generic - Is it possible at all??
 
C

Chris Smith

public class A<T>
{
T t ;
public T getValue()
{
return t;
}
}

public class B
{
A a; // How to declare generic A here
public <T> A<T> getA()
{
return a;
}
}


I know this will not work. Is there a way I can get it working with
wildcards.
I am not 100% clear with generic - Is it possible at all??

If I understand you correctly, then no it's not possible, at least
without warnings. That's because it's not type-safe. You are basically
saying that you want B to not keep track of the type parameter, and then
be able to return the object as if it had any type parameter and have
the compiler be okay with it. That's exactly the kind of problem that
generics were meant to solve. You certainly can do this:

public class B
{
A<?> a;
public A<?> getA() { return a; }
}

That's okay because you aren't pretending to know anything about a.
And, of course, you can do this:

public class B<T>
{
A<T> a;
public A<T> getA() { return a; }
}

That's okay because you really do know something about a. The only
thing that's truly impossible is to throw away knowledge of a's type,
and then go on as if you still know it by trying to return a as a
specific type.

What you're attempting is actually somewhat close to capture conversion.
If you had an a for which you don't know the type argument, you can
introduce an arbitrary type name to represent it for the purposes of a
calculation. However, you can't then return something typed with that
arbitrary name, since the name is meaningless outside of the method
which resulted in use of capture conversion.
 
N

nramnath

Hai,
Thanks for the reply. I too know about that, but just wanted to
confirm.
Thanks
Ramnath
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top