I am using getters and setters to for the purpose of encapsulation.
public class Student {
private String studentID;
private String studentName;
private String address;
public Student(){
//default constructor
}
public Student(String studentID, String studentName, String address) {
super();
this.studentID = studentID;
this.studentName = studentName;
this.address = address;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
the variables studentID, studentName and address are declared as private, with the intention of encapsulation.
but we could also do the same task by making the variable accessibility level from private to public, is it really helps to apply encapsulation by the use of setters and getters?
only I can understand the use of getter and setter is users of the class dows not need to have an idea about the names of the variables used in the class as setters and getters makes sense to the users of the class
ex- objectofStudentClass.setStudentID("S0001");
Is there any difference between main difference between making getters and setters instead if making the variable access level to public.
Question 2: also here I have made parameterized constructor matching to the variables/fields in the class Student. is that throw away the concept of encapsulation?