问题
How can I cast two extends class like that in java?
class B extends Object{
}
class C extends Object{
}
B b = new B();
C c = (C)b;//Cannot cast from B to C
回答1:
You can't. Consider a slight rename:
class Ford extends Car {
}
class Chevrolet extends Car {
}
Ford ford = new Ford();
Chevrolet chevrolet = (Chevrolet) ford;
Both are, however, a Car so you can say
Car car = ford;
but not any more than that.
回答2:
The closest you can come is to use interfaces
class B extends Object implements Thing {}
class C extends Object implements Thing {}
B b = new B()
Thing c = (Thing)b
As others have indicated you cannot do what you are trying with just classes.
回答3:
You can't cast an object B to C, because B is not a C, the best you can infer is that it's an Object. Here's another analogy:
class Animal {
public void eat();
}
class Dog extends Animal {
public void bark();
}
public Cat extends Animal {
public void meow();
}
Say you have:
Cat sprinkles = new Cat();
// this doesn't make sense
Dog aDog = (Dog) sprinkles;
aDog.bark(); // can't do this because sprinkles can't bark()
// but this does
Animal myCat = (Animal) sprinkles;
myCat.eat(); // but it can eat()
回答4:
You cannot do that since b is not an instance of class C. It is only possible to cast an object into a super-class or a super-interface.
回答5:
You categorically cannot do that. You can only cast if the type to which you are casting actually represents the ancestry of the target. In this case, B simply is not an instance of C (and vice versa). The real question is why would you want to? And what are you actually trying to accomplish?
回答6:
In the given code, class B and class C are not in a "is-a" relationship, so they cannot be casted to each other.
The only thing that B and C has in common is that they are both subclasses of Object, therefore, they can both be casted to Object. In otherwords, B is-a Object and C is-a Object:
B b = new B();
Object ob = (Object)b;
C c = new C();
Object oc = (Object)c;
As a counterexample to what is being done, imagine this case:
class B extends Object {
public void doSomething();
}
class C extends Object {
public void doAnotherThing();
}
In this case, what is the following code supposed to do?
C realC = new C();
realC.doSomething(); // This is OK.
B c = (B)realC;
c.doSomething(); // ???
Since the object made from class C doesn't have a doSomething method, what would it do?
It can be seen that just because B and C have a common ancestor does not mean that they can be interchangeable with each other.
Therefore, what is attempted in the code above cannot be performed.
回答7:
but...giving this hierarchy
class X {}
class Z extends X{}
class Y extends X{}
X z = new Z();
X y = new Y();
Z y2 =(Z)y;
Why is alloweb by the compiler the casting between Z and Y? It not works at runtime obviously cos Z is not a Y.
来源:https://stackoverflow.com/questions/3798663/casting-subclasses-extending-the-same-original-class