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
You can try to convert the super class variable to the sub class type by simply using the cast operator. But, first of all you need to create the super class reference using the sub class object and then, convert this (super) reference type to sub class type using the cast operator.
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
Java doesn't allow assigning a superclass object to a subclass one. To do so would require explicit casting, or known as downcasting.
In java object typecasting one object reference can be type cast into another object reference. The cast can be to its own class type or to one of its subclass or superclass types or interfaces.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With