wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Defining Generics of subclassed objects? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Defining Generics of subclassed objects?" Watch "Defining Generics of subclassed objects?" New topic
Author

Defining Generics of subclassed objects?

Raymond Holguin
Ranch Hand

Joined: Aug 11, 2009
Posts: 77
I have a situation that I can't seem to figured out.

ClassA
ClassB extends ClassA

I want to do the following but I cannot.

Set<ClassA> foo;
Set<ClassB> = Set<ClassA>;

I get
Type mismatch: cannot convert from java.util.Set<ClassA> to java.util.Set<ClassB>

I tried doing this and it works....but I cannot Iterate over the Set so its useless to me
Set<ClassA> foo;
Set<? extends ClassA> = Set<ClassA>;
Type mismatch: cannot convert from element type capture#3-of ? extends ClassA to ClassB

how can I accomplish this if possible?? im tryign to migrate an app from java 1.4 to java6 and this is road blocking me.

Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

You are trying to convert from the subclass to the superclass, that doesn't work in Java.

Change it to:
Set<ClassA> mySet = Set<ClassB>;

That doesn't work either as I just realized. Sorry.

Hunter


"If the facts don't fit the theory, get new facts" --Albert Einstein
Raymond Holguin
Ranch Hand

Joined: Aug 11, 2009
Posts: 77
thanks for your help, but after further review of the code i realized i misunderstood the situation. the problem is resolved now.
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

(It's good to follow up with the solution so that other readers, or people that land here via search result, know what the issue was.)
Raymond Holguin
Ranch Hand

Joined: Aug 11, 2009
Posts: 77
yes your correct, my apologies.

Turns out
Set<ClassA> foo;
Set<ClassB> = foo;

was never the situation...foo actually was Set<ClassB> the whole time.
Set<ClassB> foo;
Set<ClassB> = foo;

which is valid of course!!

I realized this after digging through the hibernate mapping for file this class. The reason why i got so confused in the place was because In the actual code ClassA and ClassB have the same name but different package locations AND you have 2 classes w/ the same name where one extend off the other LOL...thus i got confused which was which.
 
wood burning stoves
 
subject: Defining Generics of subclassed objects?
 
Similar Threads
Method Overriding doubt
Question on Constructor, instance var & static var
Inherited main method question
Generics: why doesn't this work for extending wildcards?
The java.lang.Object class