Which is the first line that will cause compilation to fail in the following program?
class MyClass extends Main { } // Filename: Main .java class Main {/*from w w w . ja v a 2 s . c om*/ public static void main (String args []){ Main a = new Main (); MyClass b = new MyClass (); a = b; // 1 b = a; // 2 a = (MyClass) b; // 3 b = (MyClass) a; // 4 } }
Select 1 option
Correct Option is : B
Casting a base class to a subclass as in : b = (MyClass) a; is also called as narrowing and needs explicit cast.
Casting a sub class to a base class as in: Main a = b; is also called as widening and does not need any casting.
For example, consider two classes: Printable and Car, where Car extends Printable Now, Printable a = new Car (); is valid because a car is definitely an Printable.
So it does not need an explicit cast.
But, Car c = a; is not valid because 'a' is an Printable and it may be a Car, a Truck, or a MotorCycle, so the programmer has to explicitly let the compiler know that at runtime 'a' will point to an object of class Car.
Therefore, the programmer must use an explicit cast:
Car c = (Car) a;