Home » JAVA Programming » Inheritance » Question
  1. What is the outcome of below code Box class?
    class Shape 
    {
    public int area()
    {
    return 1;
    }
    }

    class Square extends Shape
    {
    public int area()
    {
    return 2;
    }
    }

    class Rectangle extends Shape
    {
    public int area()
    {
    return 3;
    }
    }

    public class Box
    {
    public static void main(String[] args)
    {
    Shape obj = new Shape();
    Square obj0 = new Square();
    Rectangle obj1 = new Rectangle();
    obj1 = (Rectangle)obj0;
    System.out.println(obj0.area());
    }
    }
    1. Compilation Error
    2. Runtime Error
    3. Default Value
    4. All of above
    5. None of these
Correct Option: A

We cannot assign one child class object to another child class variable.

Box.java:32: error: incompatible types: Square cannot be converted to Rectangle
obj1 = (Rectangle)obj0;
^
1 error



Your comments will be displayed only after manual approval.