Avatar ·

Why are getters and setters (accessors) needed in Java if you can just make fields public?

Hi everyone! I started learning Java and OOP, and I have a question. I often see that in code, getters and setters are written for each class field. For example: ```java public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ``` But you can do it simpler: ```java public class Person { public String name; public int age; } ``` And access directly: `person.name = "Vasya"`. This is shorter and clearer! Why waste time writing these methods? I understand that this is somehow related to encapsulation, but