Java OCA OCP Practice Question 757

Question

Consider the following two classes (in the same package but defined in different source files):

public class Square  { 
    double side = 0; 
    double area; 

    public Square (double length){        this.side = length;     } 

    public double getSide ()  {  return side;     } 

    public void setSide (double side)  {  this.side = side;    } 

    double getArea ()  {   return area;    }  
} 
public class Main  { 
    public static void main (String [] args) throws Exception  { 
        Square sq = new Square (10.0); 
        sq.area = sq.getSide ()*sq.getSide (); 
        System.out.println (sq.getArea ()); 
     } //from  ww  w .ja  v a  2s .  c  o  m
} 

You are assigned the task of refactoring the Square class to make it better in terms of encapsulation. What changes will you make to this class?

Select 4 options

A. Add a calculateArea method: //from  w ww .  j  a  va  2  s . c  om

private void calculateArea (){ 
  this.area = this.side*this.side; 
} 

B. Make side and area fields private. 

C. Change setSide method to: 

public void setSide (double d){ 
   this.side = d; 
   calculateArea (); 
} 

D. Make the getArea method public. 

E. Add a setArea () method: 

public void setArea (double d){ area = d;  } 


Correct Options are  : A B C D

Note

There can be multiple ways to accomplish this.

The exam asks you questions on the similar pattern.

The key is that your data variable should be private and the functionality that is to be exposed outside should be public.

Your setter methods should be coded such that they don't leave the data members inconsistent with each other.




PreviousNext

Related