Java OCA OCP Practice Question 1897

Question

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

class Main{//from ww w .jav a  2  s  .  c o m
   static Main ref;
   String [] v;
   public static void main (String args []){
      ref = new Main ();
      ref.m (args);
    }
   public void m (String [] args){
      ref.v = args;
    }
}

Select 1 option

  • A. The program will fail to compile, since the static method main is trying to call the non-static method m.
  • B. The program will fail to compile, since the non-static method m cannot access the static member variable ref.
  • C. The program will fail to compile, since the argument args passed to the static method main cannot be passed on to the non-static method m.
  • D. The program will fail to compile, since method m is trying to assign to the non-static member variable 'v' through the static member variable ref.
  • E. The program will compile and run successfully.


Correct Option is  : E

Note

For A.

The concept here is that a non-static method (i.e. an instance method) can only be called on an instance of that class.

Whether the caller itself is a static method or not, is immaterial.

The main method is calling ref.m(); - this means the main method is calling a non-static method on an actual instance of the class Main (referred to by 'ref').

Hence, it is valid.

It is not trying calling it directly such as m() or this.m(), in which case, it would have been invalid.




PreviousNext

Related