I have two classes:
class Base {
public String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class Derived extends Base {
public String getValue() {
return name + " foo";
}
}
And an object created:
Base foo = new Base();
foo.setName("John");
Derived bar = (Derived) foo;
This simple example gives ClassCastException
exception:
java.lang.ClassCastException: Base cannot be cast to Derived
Is it possible somehow to extend existing object with extra read-only methods ?
With Base foo = new Base();
you're saying that you have a Cat, but all of the sudden you're trying to convert it to Persian cat, which would have succeeded, if all the cats were Persian ones. This is not true and that's why you get a ClassCastException
.
You have to do:
Base foo = new Derived();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With