-
What is the outcome of below code Output class?
class Shape
{
public int area()
{
return 2;
}
}
class Square extends Shape
{
public int area()
{
return 5;
}
}
class Rectangle extends Shape
{
public int area()
{
return 7;
}
}
public class Output
{
public static void main(String[] args)
{
Shape obj = new Shape();
Square obj0 = new Square();
Rectangle obj1 = new Rectangle();
obj1 = (Rectangle)obj;
System.out.println(obj0.area());
}
}
-
- Compilation Error
- Runtime Error
- Default value
- 7
- 5
Correct Option: B
ClassCastException is thrown as we cannot assign parent object to child variable.
Exception in thread "main" java.lang.ClassCastException: Shape cannot be cast to Rectangle
at Output.main(Output.java:32)