0
public class Main {
    public static void main(String[] args) {
        Vehicle vehicle = new Vehicle();
        vehicle = (car) Vehicle;
    }
}

class Vehicle {
   static void transport() {

    }
}

class Car extends Vehicle {
    int age;
    String brand;
}

i understand that java implicitly upcasts, but I want to downcast this Vehicle instance and make it a Car. what am i doing wrong?

leafhous
  • 23
  • 3

1 Answers1

1

Downcasting doesn't change what class the object is — it only changes what the compiler knows at compile-time. If you have a Vehicle which is not a Car (as you do, since you instantiated it as new Vehicle()), then you can't downcast it; any attempt to will result in a ClassCastException at runtime.

Other than that, what you're doing wrong is that you're downcasting using (car) instead of (Car). Java is case-sensitive.

yshavit
  • 42,327
  • 7
  • 87
  • 124