Java OCA OCP Practice Question 1413

Question

Consider the following code appearing in the same file:

class MyClass  { 
    private int x = 0, y = 0; 
    public MyClass (int x, int y){ 
        this.x = x; this.y = y; 
     } /*from   w w  w.  ja  v a 2s  . c om*/
} 
public class Main  { 
    public static void main (String [] args) throws Exception  { 
        MyClass d = new MyClass (1, 1); 
        //add code here 
     } 
} 

Which of the following options when applied individually will change the MyClass object currently referred to by the variable d to contain 2, 2 as values for its data fields?

Select 1 option

A. Add the following two statements  : /*from www.ja  v a  2  s .  co  m*/
   d.x = 2; 
   d.y = 2; 

B. Add the following statement: 
   d = new MyClass (2, 2); 

C. Add the following two statements: 
   d.x += 1; 
   d.y += 1; 

D. Add the following method to MyClass class: 
   public void setValues (int x, int y){ 
      this.x .setInt (x);   this.y.setInt (y); 
   } 
   Then add the following statement: 
   d.setValues (2, 2); 
   
E. Add the following method to MyClass class: 
    public void setValues (int x, int y){ 
      this.x = x;   this.y = y; 
    } 
    
    Then add the following statement: 
    
    d.setValues (2, 2); 


Correct Option is  : E

Note

For Option A.

Note that x and y are private in class MyClass. Therefore, you cannot access these members from any other class.

For Option B.

This will create a new MyClass object and will not change the original MyClass object referred to be d.

For Option C.

Note that x and y are private in class MyClass. Therefore, you cannot access these members from any other class.

For Option D.

x is primitive int.You cannot call any methods on a primitive. so this.x.setInt(...) or this.y.setInt(...) don't make any sense.

For Option E.

This is a good example of encapsulation where the data members of MyClass class are private and there is a method in MyClass class to manipulate its data.

Compare this approach to making x and y as public and letting other classes directly modify the values.




PreviousNext

Related