Inheritance


  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. View Hint View Answer Discuss in Forum

    NA

    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