I'm a beginner programmer in Java, so this may sound like a simple and rather silly question:
In Java, is it better to use a method to get a property value or just use the property itself?
To see what I mean, look at this example from a page from the Oracle Java Tutorials about Lambda Expressions:
processPersons(
roster,
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25,
p -> p.printPerson()
);
I'm just wondering, what would be the use of evoking p.getGender()
and p.getAge()
when just using p.gender
and p.age
should have the right values? They can't have multiple values or anything that could prevent them from just using the properties. (p.printPerson()
is fine because it might print out multiple property values.)
I mean, to run the above code, they would need to have a constructor to assign properties and extra methods just to return the property values, like so:
public class Person {
public String name;
public int age;
public String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
// assign some other properties for "printperson()" to print out
}
public String printPerson() {
return name; // and maybe return some other values
}
// need the methods below just to return property values??? are they unnecessary??
public String getGender() {
return this.gender; // can't they use "p.gender" to get this value?
}
public int getAge() {
return this.age; // can't they use "p.age" to get this value?
}
}
Some of my reasoning is assumptions from my limited programming knowledge, so please correct me if I'm wrong.
Is there something I'm missing, a reason why to use methods to get property values? Or was it just used as a example? Because it would seem much simpler to not have to evoke methods and slow the program down.
Any thoughts are appreciated.