Home » JAVA Programming » Inheritance » Question
  1. 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());
    }
    }
    1. Compilation Error
    2. Runtime Error
    3. Default value
    4. 7
    5. 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)



Your comments will be displayed only after manual approval.