What three modifications are necessary to ensure that the class is being properly encapsulated?

Given:
<code>
public class Circle {
double radius;
public double area:
public Circle (double r) { radius = r;}
public double getRadius() {return radius;}
public void setRadius(double r) { radius = r;}
public double getArea() { return /* ??? */;}
}
class App {
public static void main(String[] args) {
Circle c1 = new Circle(17.4);
c1.area = Math.PI * c1.getRadius() * c1.getRadius();
}
</code>
This class is poorly encapsulated. You need to change the circle class to compute and return the area
instead.
What three modifications are necessary to ensure that the class is being properly encapsulated?

Given:

public class Circle {
double radius;
public double area:
public Circle (double r) { radius = r;}
public double getRadius() {return radius;}
public void setRadius(double r) { radius = r;}
public double getArea() { return /* ??? */;}
}
class App {
public static void main(String[] args) {
Circle c1 = new Circle(17.4);
c1.area = Math.PI * c1.getRadius() * c1.getRadius();
}

This class is poorly encapsulated. You need to change the circle class to compute and return the area
instead.
What three modifications are necessary to ensure that the class is being properly encapsulated?

A.
Change the access modifier of the setradius () method to private

B.
Change the getArea () method
public double getArea () { return area; }

C.
When the radius is set in the Circle constructor and the setRadius () method, recomputed the area
and store it into the area field

D.
Change the getRadius () method:
public double getRadius () {
area = Math.PI * radius * radius;
return radius;
}

Explanation:

A: There is no need to have SetRadius as public as the radius can be set through the Circle method.
B: We need to return the area in the GetArea method.
C: When the radius changes the Area must change as well.
Incorrect answer:
D: the GetRadius() method does not change the radius, so there is no need to recomputed the area.



Leave a Reply 3

Your email address will not be published. Required fields are marked *


Alex

Alex

The only correct answers are B and C.
The A is false, because if you set a private method into Circle class it can’t be reachable on App class and so you can never set a new radius value.
Private has to be the radius variable.

Kalil Peixoto

Kalil Peixoto

Alex, it stands correct as A,B,C. You need to set setRadius as private so all the operations regarding the radius and the area will be made only at the Circle class, starting from the constructor. This is what improves the encapsulation on the program.

sully

sully

Agreed A, B, C