OCA Java SE 8 Method - OCA Mock Question Method 26








Question

Which of the following complete the constructor so that this code prints out 222?

     public class Main {  
       int myValue; 
       public Main(int myValue) { 
         // INSERT CODE HERE 
       }  
       public static void main(String[] args) { 
         System.out.println(new Main(222).myValue); 
       } 
     } 
  1. myValue = myValue;
  2. myValue = this.myValue;
  3. this.myValue = myValue;
  4. myValue = super.myValue;
  5. super.myValue = myValue;
  6. None of the above.




Answer



C.

Note

Inside the constructor myValue refers to the constructor parameter not the instance variable.

The instance variable is hidden since they have the same name.

this.myValue tells Java to use the instance variable.

In the main() method, myValue refers to the instance variable.