views:

57

answers:

6

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
A: 

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?

Kirk Woll
A: 

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.

coobird
+2  A: 

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.

hvgotcodes
+1  A: 

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.

Jcs
+4  A: 

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 anymore than that.

Thorbjørn Ravn Andersen
Calling a Chevrolet a Car is a bit of an overstatement, but OK...
NullUserException
+1  A: 

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()
NullUserException