Java OCA OCP Practice Question 1459

Question

Given:

class Main{ //from  ww w .j av a 2s .  co  m
    public int base; 
    public int height; 
    private final double v; 

    public  void setAngle (double a){  v = a;   } 
     
    public static void main (String [] args)  { 
        Main t = new Main (); 
        t.setAngle (90); 
     } 
} 

Select 1 option

  • A. the value of v will not be set to 90 by the setAngle method.
  • B. An exception will be thrown at run time.
  • C. The code will work as expected setting the value of v to 90.
  • D. The code will not compile.


Correct Option is  : D

Note

The given code has two problems:

A final field must be explicitly initialized by the time the creation of an object of the class is complete.

So you can either initialize it immediately:

private final double v = 0; 

or you can initialize it in the constructor or an instance block.

Since v is final, you can't change its value once it is set.

Therefore the setAngle() method will also not compile.




PreviousNext

Related