JavaBeans: Difference between revisions

Content deleted Content added
JavaBean Example: edited and tested; removed unused "age" property
Line 18:
== JavaBean Example ==
<pre>
// PersonBean.java
 
public class PersonBean implements java.io.Serializable {
private String name;
private int age;
private boolean deceased;
 
// OurDefault constructor. Note that it (takes no arguments (a default constructor).
public PersonBean() {
// Our constructor. Note that it takes no arguments (a default constructor).
}
 
public String getName() { return (this.name); }
public int getAge() { return (this.agename); }
}
public void setName(String n) {
this.name = n;
}
// note slightly differentDifferent semantics for a boolean field (*is* vs. *get*)
 
public voidboolean setAgeisDeceased(int a) {
return (this.age = adeceased);
}
 
public void setDeceased(boolean deceased) {
this.deceased = deceased;
}
 
public String getName() { return (this.name); }
public int getAge() { return (this.age); }
// note slightly different semantics for a boolean field (*is* vs. *get*)
public boolean isDeceased() { return (this.deceased); }
}
</pre>
 
<pre>
PersonBean person = new PersonBean();
// TestPersonBean.java
person.setName("Bob");
 
person.setAlive(false);
public class TestPersonBean {
System.out.println(person.getName() + (person.isDeceased() ? " [deceased]");
public static void main(String[] args) {
 
PersonBean person = new PersonBean();
person.setName("Bob");
person.setDeceased(true);
 
// Output: "Bob [deceased]"
System.out.print(person.getName());
System.out.println(person.getName() + (person.isDeceased() ? " [deceased]" : "");
}
}
</pre>