我是一名 Java 初学者,所以这可能听起来是一个简单且相当愚蠢的问题:
在 Java 中,使用方法获取属性值好还是仅使用属性本身更好?
要明白我的意思,请查看 Oracle Java Tutorials 页面中的这个示例。关于Lambda Expressions :
processPersons(
roster,
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25,
p -> p.printPerson()
);
我只是想知道,唤起有什么用p.getGender()
和p.getAge()
仅使用 p.gender
时和p.age
应该有正确的值(value)观?他们不能有多个值或任何可能阻止他们使用属性的东西。 ( p.printPerson()
很好,因为它可能会打印出多个属性值。)
我的意思是,要运行上面的代码,他们需要有一个构造函数来分配属性和额外的方法只是为了返回属性值,如下所示:
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?
}
}
我的一些推理是基于我有限的编程知识的假设,所以如果我错了,请纠正我。
我是否遗漏了一些东西,即为什么使用方法来获取属性值的原因?或者它只是用作示例?因为不必调用方法并减慢程序速度似乎要简单得多。
任何想法都值得赞赏。
最佳答案
引用: Effective Java Item 14 在公共(public)类中,使用访问器方法,而不是公共(public)字段。
if a class is accessible outside its package, provide accessor methods, to preserve the flexibility to change the class’s internal representation. If a public class exposes its data fields, all hope of changing its representation is lost, as client code can be distributed far and wide.
关于java - 使用方法 "getValue()"或获取属性 "value"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24641512/