Win a copy of Event Streams in Action this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Derived class, ClassCastException

 
Ranch Hand
Posts: 86
  • 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.
 
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: 86
  • 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;
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • 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 ]
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!