What will be the output of the following Java program?

class A 
    {
        int i;
        void display() 
        {
            System.out.println(i);
        }
    }    
    class B extends A 
    {
        int j;
        void display() 
        {
            System.out.println(j);
        }
    }    
    class inheritance_demo 
    {
        public static void main(String args[])
        {
            B obj = new B();
            obj.i=1;
            obj.j=2;   
            obj.display();     
        }
   }

a) 0
b) 1
c) 2
d) Compilation Error

1 thought on “What will be the output of the following Java program?”

  1. c
    Explanation: Class A & class B both contain display() method, class B inherits class A, when display() method is called by object of class B, display() method of class B is executed rather than that of Class A.
    output:
    $ javac inheritance_demo.java
    $ java inheritance_demo
    2

Leave a Comment