Java OCA OCP Practice Question 1881

Question

What will be the result of attempting to compile and run the following program?

class MyClass {//from w w  w .  j ava2s.  co m
   int i = 10;

   int m1() {
      return i;
   }
}

class MyClass2 extends MyClass {
   int i = 20;

   int m1() {
      return i;
   }
}

class MyClass3 extends MyClass2 {
   int i = 30;

   int m1() {
      return i;
   }
}

public class Main {
   public static void main(String args[]) {
      MyClass o1 = new MyClass3();
      MyClass2 o2 = (MyClass2) o1;
      System.out.println(o1.m1());
      System.out.println(o2.i);
   }
}

Select 1 option

  • A. The program will fail to compile.
  • B. Class cast exception at runtime.
  • C. It will print 30, 20.
  • D. It will print 30, 30.
  • E. It will print 20, 20.


Correct Option is  : C

Note

variables are shadowed and methods are overridden.

Which variable will be used depends on the class that the variable is declared of.

Which method will be used depends on the actual class of the object that is referenced by the variable.

So, in line o1.m1 (), the actual class of the object is MyClass3, so MyClass3's m1 () will be used.

So it returns 30.

In line o2.i, o2 is declared to be of class MyClass2, so MyClass2's i is used.

So it returns 20.




PreviousNext

Related