Citigroup Interview Question
Country: India
Interview Type: In-Person
Second code will run. Creating object of type A and then downcasting to B, assigning it to type B is completely correct. First code for obvious reasons will not run (compile time problem).
Neither the original code nor the proposed edit will work. The issue is that your object is of type A, and is not of type B. You therefore cannot assign it to a variable that holds an object of type B.
- eugene.yarovoi April 06, 2014This would work in the other direction: A a = new B() works just fine and doesn't even need any casting. That's because, since B is a subclass of A, any object of type B is also of type A. Since the new instance of B is also of type A, we can assign it to a variable that holds an object of type A.
You might have an easier time understanding this if you replace A and B with Car and Chevy. If you make a new Car, it might not be a Chevy, so putting it in a place reserved for only Chevys is not always correct and won't be allowed. But if you make a new Chevy, it's always a Car, so putting it into a place for Cars is perfectly fine.
At no point has casting entered this discussion yet, so you might be wondering what that's used for. Well, it can't be used to transform any Car into a Chevy. You can't just do, as you did with A and B above, Chevy c = (Chevy) new Car();. Java isn't some kind of magical wizard that can somehow transform a Car into a Chevy if it isn't one already. A Chevy might have additional data associated with it -- where would that data come from when making the conversion? In this case, the operation would result in a ClassCastException, letting you know that the conversion failed because the object isn't of the type you're trying to cast it to.
A cast would only work in a situation where you know a priori that something is of a certain type, but yet the object is currently being stored in a variable whose type is some supertype. For example, let's say we wrote Car c = new Chevy(). We know c is a Chevy, even though we're holding it in a variable for Cars. We could now do Chevy ch = (Chevy) c. When we do this, Java will verify that the conversion we're attempting is valid (that c really is a Chevy and not any other kind of Car) before making the assignment, and a ClassCastException will be thrown if c is not a Chevy as expected.