Java Bean
March 10, 2008 ・0comments
JavaBeans are classes written in the Java programming language conforming to a particular convention. They are used to encapsulate many objects into a single object (the bean), so that the bean can be passed around rather than the individual objects.The specification by Sun Microsystems defines them as "reusable software components that can be manipulated visually in a builder tool".
Example:
// PersonBean.java
public class PersonBean implements
java.io.Serializable {
private String name;
private boolean deceased;
// No-arg constructor (takes no arguments).
public PersonBean() {
}
// Property "name" (note capitalization)
readadble/writable
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
// Property "deceased"
// Different syntax for a boolean field
(is vs. get)
public boolean isDeceased() {
return this.deceased;
}
public void setDeceased(boolean deceased) {
this.deceased = deceased;
}
}
// TestPersonBean.java
public class TestPersonBean {
public static void main(String[] args) {
PersonBean person = new PersonBean();
person.setName("Bob");
person.setDeceased(false);
// Output: "Bob [alive]"
System.out.print(person.getName());
System.out.println(person.isDeceased()
? " [deceased]" : " [alive]");
}
}
Post a Comment