What will be the output of the following Java program?

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

a) 1
b) 2
c) 3
d) 4

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

  1. b
    Explanation: r is reference of type A, the program assigns a reference of object obj2 to r and uses that reference to call function display() of class B.
    output:
    $ javac Dynamic_dispatch.java
    $ java Dynamic_dispatch
    2

Leave a Comment