简体   繁体   中英

JavaBeans: What's the difference between an attribute and a property?

In the JavaBean section of my revision list it states that I should know "the difference between an attribute and a property". I can't really find a difference between the two. I'm aware that JavaBeans use properties and normal Java classes use attributes (or at least that's what I was taught to call them) but I can't see a real difference.

Is it to do with getter/setter methods?

Thanks

Examples

Property and attribute are equivalent

private int age;

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

Property age translates to personAge attribute

private int personAge;

public int getAge() {
    return personAge;
}

public void setAge(int age) {
    this.personAge = age;
}

Property is synthesized, there is no attribute

In this case the property is read-only:

private int age;
private Sex sex;

public boolean isFemaleAdult() {
    return sex == Sex.FEMALE && age >= 18
}

I found few intereseting hints in Tapestry documentation :

A property is not the same as an attribute ... though, most often, each property is backed up by an attribute.

and later:

Another common pattern is a synthesized property. Here, there is no real attribute at all, the value is always computed on the fly.

In broad terms, properties corresponds to method pairs atype getXXX() / void setXXX(atype ) . Attributes refer to member fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM