简体   繁体   中英

I have some issue about casting in java

public class A {
    private String superStr;

    public String getSuperStr() {
        return superStr;
    }

    public void setSuperStr(String superStr) {
        this.superStr = superStr;
    }   
}
public class B extends A {
    private String subStr;

    public String getSubStr() {
        return subStr;
    }

    public void setSubStr(String subStr) {
        this.subStr = subStr;
    }   
}

And I expect result likes below

    public static void main(String[] args) {

        A a = fuc();

        B b = new B();

        b = (B) a;

        b.setSubStr("subStr");

        System.out.println(a.getSuperStr() +  b.getSubStr());       
    }

    private static A fuc() {
        A  a = new A();
        a.setSuperStr("super");

        return a;
    }

but java.lang.ClassCastException is ocuured.

How can I cast this? I want use subclass variable and super class variable.

thank you

How can I cast this?

You can't. You can only cast when the object in question has an "is a" relationship with the type. In your case, you have an A object (the one from fn ), which is not a B . (All B objects are A s, because B extends A , but not all A objects are B s.)

Consider: Let's call B Bird and A Animal : A Bird is an Animal , but not all Animal s are Bird s. So we can treat all Bird s as Animal s, but we cannot treat all Animal s as Bird s. When you're using a variable of a given type to refer to an object, you're treating the object as being of that type (eg, B b = (B)a tries to treat the Animal a as a Bird ).


Side note: There's no point to the indicated part of the code:

B b = new B();
// ^^^^^^^^^^
b = (B) a;

Since the very next line assigns to b (well, it would if it would compile), there's no purpose served by doing new B() and assigning that to b just beforehand. (Unless the B constructor has side-effects, which is generally a Bad Idea™.)

Casting a particular object to another types does not magically convert it into an instance of that class (or at least not in Java ); Therefore, the object referenced by variable a does not eg have the field subStr to use despite that the object referenced by b after executing B b = new B(); does.

The others have already explained why you can't do that. I'm here to give you a simple alternative. Your B class could have a constructor that had an A as argument and you would simply wrap that A so you could "transform" it to a B. Using that your code would look way more clean, it would actually work and you were following a good design pattern. For more information check the Decorator Pattern

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM