Search code examples
theorycompiler-theory

In object oriented programming, is it safe to always downcast a variable?


This is more about compiler theory, given I'm playing around with making one. I'm wondering if it is theoretically safe to always downcast a variable within a subclass.

class Car {
  BodyType myBodyType;
}
class Corvette extends Car {
  FourWheels myBodyType;
  // normally this is rejected by most compilers
  // redefinition of myBodyType;
}

class BodyType {}
class FourWheels extends BodyType {}

Currently in traditional OO programming, we always have to downcast myBodyType to FourWheels if we know that myBodyType is always that specific type. If this is done automatically by the compiler, would it be safe?


Solution

  • No, this won't be safe, because right now nothing stops a user from writing:

    Car car = new Corvette();
    car.myBodyType = new TwoWheels();
    

    And now downcasting myBodyType in car to be of type FourWheels can lead to problematic behavior.

    The only way that you can rely on myBodyType never being of an incorrect type is by having guarantees that a value of an incorrect type is never written into it - e.g. by making it a read-only value that is set during construction.

    By the way, in a Java-like languages, a more elegant approach from the user would be something like:

    class Car<MyBodyType extends BodyType> {
      MyBodyType myBodyType;
    }
    class Corvette extends Car<FourWheels> {
      ...
    }