aspose file tools*
The moose likes Beginning Java and the fly likes please help, class casting problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "please help, class casting problem" Watch "please help, class casting problem" New topic
Author

please help, class casting problem

Josh Wetzel
Greenhorn

Joined: Sep 30, 2000
Posts: 3
I'm having a lot of difficulty casting from one type to antother. My code compiles but I get a class cast exception error at runtime. Can anyone tell me why? Thanks in advance!!
FILE 1
import java.util.*;
public class SetPlusTest {
public static void main(String[] args) {
SetPlus s1 = (SetPlus) new HashSet();

for(int i=0; i<=4; i++) {
s1.add(new Integer(i));
}

SetPlus s2 = (SetPlus) new HashSet();
for(int i=0; i<=8; i+=2) {
s2.add(new Integer(i));
}
Set u = s1.union(s2);
System.out.println(s1 + " union " + s2 + " is " + u);
}
}
FILE 2
import java.util.*;
interface SetPlus extends Set {
SetPlus union(SetPlus s2);
}
FILE 3
import java.util.*;
public class HashSetPlus extends HashSet implements SetPlus {
public SetPlus union(SetPlus s2) {
SetPlus z = new SetPlus(s2);
z.addAll(this);
z.addAll(s2);
return z;
}
}
}
Andy Ceponis
Ranch Hand

Joined: Dec 20, 2000
Posts: 782
Well your file 1 class name is SetPlusTest, but everywhere else you refer to it as SetPlus. You cant cast anything with a class that doesnt exist. Unless SetPlus is a class that im unaware of which it might be...
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

Try thinking 'is a'.
It is NOT valid to say that a HashSet IS A SetPlus.
A HashSetPlus IS A SetPlus, but a HashSet is not.
Therefore what you want is:

or thereabouts.
Dave.
Jyotsna Clarkin
Ranch Hand

Joined: Jan 26, 2001
Posts: 158

or thereabouts.
Dave.
[/b]
</BLOCKQUOTE>
Here's a diagram to clarify the stuff Dave said
<html>
<head>
<body>
<pre>

Set

|
|
HashSet SetPlus
| |
| |
HashSetPlus
legend: blue dash -> extends
red dash -> implements


</body>
</head>
</html>

You do not need an explicit cast

will work.
You also CANNOT instantiate an interface

I changed this to

These changes got your program working. Let me know if you can't fix it and I'll post the corrected code.
regards,
Jyotsna

[This message has been edited by Jyotsna Clarkin (edited May 10, 2001).]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: please help, class casting problem