I have a class called Student and here is the code:-
public class Student {
public String name;
}
And from another class, I access the name.
public class Example {
public static void main(String[] args) {
Student s = new Student();
s.name = "David";
System.out.println(s.name);
}
}
But I have heard and seen many codes in many books where they say to make the variables private and use methods to access them like:-
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And,
public class Example {
public static void main(String[] args) {
Student s = new Student();
s.setName("David");
System.out.println(s.getName());
}
}
I want to know WHY and what's the DIFFERENCE between them. Why is using methods to manipulate state considered healthier?