Given the following class:
Which two changes would encapsulate this class and ensure that the area field is always equal to length * height whenever the Rectangle class is used?
A. Call the setArea method at the end of the setHeight method.
B. Call the setArea method at the beginning of the setHeight method.
C. Call the setArea method at the end of the setLength method.
D. Call the setArea method at the beginning of the setLength method.
E. Change the setArea method to private.
F. Change the area field to public.
AE
It seems to me that the question is not correct and the offered choices are not right. The class looks already encapsulated. Making the setArea() method private, and calling it for either setHeight() or setLength() means that the area will be always 0.0. The reason is neither the length nor the height have been initialized. So they are 0 at the beginning. Therefore, if we call setLength() for example, and we set the length to 10, and then calling setArea(), the result will be 0!! because the height is still 0!
public class Rectangle{
private double length,height,area;
public void setLength(double len){
this.length = len;
}
public void setHeight(double hei){
this.height = hei;
}
public double getArea(){
return length * height;
}
public static void main(String[] args){
Rectangle rect = new Rectangle();
rect.setLength(10.0); rect.setHeight(10.0);
System.out.println(rect.getArea());
}
}
I would better write a getter method that returns a double value (in this case multiplication of length and height). But anyways, in the above case – you should call the setArea() method then , print out the value of area. Because without actually calling the method setArea, value of area would be 0.0 by default.
A, C
This code here I think is poorly written, and doesn’t make much sense. The reason you’re getting 0.0 every time is because of the order the methods are being called in.
In your main method setLength(20) is the first method called. setArea() is within your setHeight method. This means when “setArea()” is called you’re doing 0.0 * 20.0 = 0.0. So whenever you call area you’re getting 0.0
public class Class26 {
private double length;
private double height;
private double area;
public void setLength(double length) {
this.length = length;
}
public void setHeight(double height) {
this.height = height;
setArea();
}
private void setArea() {
area = length*height;
}
public static void main(String args[]) {
Class26 rectangle = new Class26();
rectangle.setHeight(20);
rectangle.setLength(200);
System.out.println(rectangle.area);
}
}
I just follow the answer but the result is 0.0. Can any one help me to understand question please?
RectangleEncapsulation rectangle = new RectangleEncapsulation();
rectangle.setLength(200); //put setLength first
rectangle.setHeight(20);
System.out.println(rectangle.area);
then the result is 4000