Java OCA OCP Practice Question 345

Question

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

public class Square {
   double side = 0;
   double area;//from   w w  w . j  a v  a2  s.c o m

   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 ()); 
     } 
} 

To refactor the Square class to make it better in terms of encapsulation.

What changes will you make to this class?

Select 2 options

A. Make setSide () method private. 
B. Make getArea () method private. 
C. Make side and area fields private. 
D. Make the side field private and remove the area field. 
E. Change getArea method to: 
   public double getArea (){ return side*side;  } 
F. Add a setArea () method. 


Correct Options are  : D E

Note

A. and B. are wrong

It should be made public so that other classes can get the area.

C. is wrong.

There is no need to keep the area field because that would amount to duplicating the data.

If you change side, the value of area will become obsolete.

F. is wrong

This is not required because area is calculated using the side.

So if you allow other classes to set the area, it could make side and area inconsistent with each other.




PreviousNext

Related