问题
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