What are Java beans?!
Sometimes developers use programming jargon that new developers have a hard time comprehending. One term I frequently hear is “bean.” All a JavaBean is, is a class used to define the attributes of a entity; examples of commonly used beans would be person, customer, and employee. A JavaBean typically only contain private attributes and the getter and setter methods to access and set those attributes respectively. Here is a simple example of what a Java bean looks like:
public class Employee {
private String firstName;
private String lastName;
private int yearsExp;
private String title;
private double salary;public String getFirstName() {
return firstName;
}public void setFirstName(String firstName) {
this.firstName = firstName;
}public String getLastName() {
return lastName;
}public void setLastName(String lastName) {
this.lastName = lastName;
}public int getYearsExp() {
return yearsExp;
}public void setYearsExp(int yearsExp) {
this.yearsExp = yearsExp;
}public String getTitle() {
return title;
}public void setTitle(String title) {
this.title = title;
}public double getSalary() {
return salary;
}public void setSalary(double salary) {
this.salary = salary;
}
}
JavaBeans are also commonly referred to as POJOs (Plain old Java objects). The terms are not entirely synonymous, as a POJO refers to a specific type of class, but is none the less often used interchangeably.
Tip: Most IDEs can automatically generate the getter and setter methods for a class' attributes, so don't waste your precious time doing it! In Eclipse just right click any where on the code screen select source>generate getters and setters, and follow the instructions. Simple as pie!
No related posts.
