The Appl class uses Square objects. Apply the "field encapsulation" technique to the fields in the Square class and change the existing code. Please suggest other solutions to improve code quality.

I got such a task at the interview. Such a code can satisfy the interviewer?

public class Square { private double x, y; private double width; public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public Square() { } public Square(double x, double y, double width) { this.x = x; this.y = y; this.width = width; } public double getPerimetr() { return 4*width; } } public class Appl { public void work() { Square square = new Square(); square.setX(2); square.setY(3); } } 

  • and what do you need? - Komdosh
  • Write code in which you encapsulate the fields of the Square class and suggest some other changes to improve the code - Nazar Sokhan
  • one
    write your attempt first, then we can help, just now it looks like a learning task - Komdosh
  • one
    And the code should not be pictures but letters - Anton Sorokin
  • one
    Encapsulation in this case is the addition of private access modifiers. The question is how to provide access to these variables, because there is also the final modifier. It is preferable almost always. In this case, initialization should be provided to the constructor, and even better to the builder. After all, according to the condition of the problem it is not said that after initialization there is a need to change the fields. In addition, in exceptional cases, you can always create a new object. But at the same time you can hint at the knowledge of the generating patterns. And you can also create an object through the static method of the interface. Think about it. - Dmitry

1 answer 1

Getters and Setters do not automatically encapsulate. Although for some reason many people think so. Rather, even the presence of setters indicates the absence of encapsulation. And by default, immutable objects must be made. Mutable ones should be done only with a concrete need (but it is better to think again in this case). In general, getters and setters are not a duty, but only a JavaBeans specification. It is not necessary to push it everywhere where necessary and not necessary.
Here's how to write easier:

 public class Square { private final double x, y; private final double width; public Square(double x, double y, double width) { this.x = x; this.y = y; this.width = width; } public double x() { return x; } public double y() { return y; } public double width() { return width; } public double perimetr() { return 4*width; } } public class Appl { public void work() { Square square = new Square(2, 3, 42); } }