Search code examples
javacastingsubclass

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

Solution

  • 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.