Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I downcast this object in java?

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading