Java OCA OCP Practice Question 397

Question

Consider the following class...

class Main{ 
   int x; 
   public static void main (String [] args){ 
      // lot of code. 
    } 
} 

Select 1 option

  • A. By declaring x as static, main can access this.x
  • B. By declaring x as public, main can access this.x
  • C. By declaring x as protected, main can access this.x
  • D. main cannot access this.x as it is declared now .
  • E. By declaring x as private, main can access this.x


Correct Option is  : D

Note

D. is a correct answer.

Because main() is a static method. It does not have 'this' !

It is not possible to access x from main without making it static.

Because main is a static method and only static members are accessible from static methods.

There is no 'this' available in main so none of the this.x are valid.




PreviousNext

Related