I have been doing assignments for college projects. At one point, I am getting confused at what is actually the use of getter and setter when you can actually use constructor methods to achieve the same results. I have searched and found many answers but not satisfactory explanation. I have laptop.java as follows
public class laptop {
private String model;
public laptop(String brand){
model=brand;
}
public String toString(){
return "Laptop Brand is: "+ model;
}
}
and the laoptopRecords.java that is calling constructor as
public class laptopRecords {
public static void main(String[] args) {
// TODO Auto-generated method stub
laptop laptop1=new laptop("Dell");
System.out.println(laptop1);
}
}
Here I am not using the getter and setter methods and I get desired result for every laptop object.
If I do in another way using getter and setter methods in laptopRecord.java as follows, I get the same result. But I am not getting what is use of getter and setter methods if actually we can achive the results with constructor as well.
laptop.java with getter and setter
public class laptop {
private String model;
public laptop(String brand){
model=brand;
}
public void setlaptop(String brand){
model=brand;
}
public String getlaptop(){
return model;
}
public String toString(){
return "Laptop Brand is: "+ model;
}
}