Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast base object to derived class

Tags:

java

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 ?

like image 732
hsz Avatar asked Jun 01 '15 12:06

hsz


1 Answers

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();
like image 149
Konstantin Yovkov Avatar answered Sep 30 '22 04:09

Konstantin Yovkov