You absolutely can use the variable directly in your example, mainly because sayName() is in the same class.
In addition, I see 3 reasons for having getters and setters:
1.) This is the principle of object-oriented programming for preserving private (private) and providing public methods for interacting with other classes.
2.) Classes with getters and setters often follow the Java beans design pattern. This template allows you to use these objects in template engines or expression languages ββsuch as JSP or Spring.
3.) In some cases, this prevents actual errors. Example:
public class DateHolder() { public Date date; public static void main(String... args) { DateHolder holder = new DateHolder(); holder.date = new Date(); System.out.println("date in holder: "+holder.date); Date outsideDateRef = holder.date; outsideDateRef.setTime(1l);
Transferring a date variable using a getter and setter, which only work with a value, not a reference, will prevent this:
public class DateHolder() { private Date date; public Date getDate() { return (Date)this.date.clone(); } public void setDate(Date date) { this.date = (Date) date.clone(); } public static void main(String... args) { DateHolder holder = new DateHolder(); holder.setDate( new Date() ); System.out.println("date in holder: "+holder.getDate()); Date outsideDateRef = holder.getDate(); outsideDateRef.setTime(1l);
source share