Converting Object of SuperClass to Sub Class

﹥>﹥吖頭↗ 提交于 2019-12-01 23:54:51

问题


I have some Code like this.

Super Class

public class Actual {
    public int x = 123;
}

Sub classes

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);
    }
}

but its giving Class Cast exception.


回答1:


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.




回答2:


Can i convert Object of Super Class into the Sub class?

No, You can do it other way only. You can assign a sub class object to super class reference only.

Reason for it is, sub class can have more functionality and more specific to a problem. If you are allowed to case a super class object to sub class, then how that super class object will get those sub class functionality?




回答3:


There were no possibility to do that. You can only have sth like this. Actual s = new Super(); or Super sp = new Super(); or Actual a = new Actual(); There are no other possibilities. Only that assigment might not throw classcast Exception.




回答4:


These are the only way to create object of your super class and sub class :

Actual act = new Actual();
Actual actual = new Super();
Actual actual2 = new Sub();

Super super1 = new Super();
Super super2 = new Sub();

Sub sub = new Sub();  

There is no other way. If your tried it will give you compile time error to cast your class OR give run time error java.lang.ClassCastException.



来源:https://stackoverflow.com/questions/22192402/converting-object-of-superclass-to-sub-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!