Java OCA OCP Practice Question 687

Question

Consider the following class written by a novice programmer.

public class Main{ 
    public int radiusA, radiusB; 
    public int sum = 100; 

    public void setRadius (int r){ 
        if (r>99) throw new IllegalArgumentException (); 
        radiusA = r; /*from w ww  .  j  a v a  2s .co m*/
        radiusB = sum - radiusA; 
         
     } 
} 

After some time, the requirements changed.

The programmer wants to make sure that radiusB is always (200 - radiusA)

instead of ( 100 - radiusA) without breaking existing code that other people have written.

Which of the following will accomplish his goal?

Select 1 option

A. Make sum = 200; 
B. Make sum = 200 and make it private. 
C. Make sum = 200 and make all fields(radiusA, radiusB, and sum) private. 
D. Write another method *setRadius2*(int r) 
   and set radiusB accordingly in this method. 
E. His goal cannot be accomplished. 
F. This class will not compile. 


Correct Option is  : E

Note

setRadius() method makes sure that radiusB is set to sum - radiusA.

So changing sum to 200 should do it.

radiusA, radiusB, and sum are public which means that any other class can access these fields directly without going through the setRadius() method.

So there is no way to make sure that the value of radiusB is correctly set at all times.

If you make them private now, other classes that are accessing the fields directly will break.

The class should have been coded with proper encapsulation of the fields in the first place.




PreviousNext

Related