将SuperClass的对象转换为子类 [英] Converting Object of SuperClass to Sub Class

查看:126
本文介绍了将SuperClass的对象转换为子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码。

超级等级

public class Actual {
    public int x = 123;
}

子类

public class Super extends Actual{
    public int x = 999;
    public int y = 12345;
}


public class Sub extends Super {
    public int x = 144;
}

所以问题是我可以将超类的对象转换为子类吗?
这个问题的权利我试过了什么?

so Question is Can i convert Object of Super Class into the Sub class? is this Right for this Question what i have tried?

public class Mid1Prob1 {
    public static void main(String[] args) {
        System.out.println("Testing...");
        int x = 3;
        Actual actual = new Super();
        System.out.println(actual.x);


        Super super1 = new Super();
        System.out.println(super1.x);


        Actual act = new Actual();

        act = new Sub();
        System.out.println(act.x);
    }
}

但它给出了Class Cast异常。

but its giving Class Cast exception.

推荐答案

您可以将Child类转换为Super类,但反之亦然。
如果车辆是超级舱而且车辆是子舱,则所有车辆(儿童)都是车辆(超级),但并非所有车辆都是车辆。

You can cast Child classes to Super classes but not vice versa. If Vehicle is Super Class and Car is a Subclass then all Cars (Child) is a Vehicle (Super) but not all Vehicle is a Car.

这篇关于将SuperClass的对象转换为子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆