• Post Reply Bookmark Topic Watch Topic
  • New Topic

Derived class, ClassCastException  RSS feed

 
Jiri Nejedly
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to modify protected attribute in some object, which si then passed to somewhere. So I made a new class this way:

class FormerClass {
protected attr;
}

public class MyClass extends FormerClass {
public ModifyAttr() {
attr = ...;
}
}

But when I use it this way:

FormerClass f = ...
MyClass m = (MyClass)f;
f.ModifyAttr();

it gives ClassCastException on 2nd line. I Don't know why. Any ideas ? Thanks.
 
Petrus Pelser
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The superclass reference must point to a reference to the subclass to succeed.
e.g.
 
Jiri Nejedly
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's a problem - object is not created by 'new', but loaded (deserialized) from file.

ois = new ObjectInputStream(is);
obj = ois.readObject();

FormerClass f = (FormerClass)obj;
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the actual object is not a MyClass object, then you cannot cast it to type MyClass.

Inheritance models an "is a" relationship - an instance of a subclass is an instance of the superclass. But the relationship only works one way.

Just like "a cow is an animal, but an animal is not necessarily a cow". A dog is an animal too, but you cannot pretend that a dog is a cow.

So if the deserialized class is of type FormerClass, then this idea of extending FormerClass and then casting the deserialized object to that is not going to work - you'll have to find another solution.
[ November 15, 2006: Message edited by: Jesper Young ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!