Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting subclasses extending the same original class

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
like image 838
MUH Mobile Inc. Avatar asked Sep 26 '10 16:09

MUH Mobile Inc.


People also ask

Can you cast super class subclass?

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.

What does a subclass inherit from a superclass?

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.

Does the assignment of a superclass to a subclass require a cast?

Java doesn't allow assigning a superclass object to a subclass one. To do so would require explicit casting, or known as downcasting.

Can you cast object to subclass Java?

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.


2 Answers

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.

like image 103
Thorbjørn Ravn Andersen Avatar answered Sep 18 '22 15:09

Thorbjørn Ravn Andersen


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.

like image 37
hvgotcodes Avatar answered Sep 19 '22 15:09

hvgotcodes