Saturday, February 13, 2016

What is a Java Bean (JB)

There are lot of confusions among people new to Java programming what is a Java Bean. What does that really mean. Is it a different type of class in Java as Enum . I also had all those questions at the beginning. So here i'm writing about what i learn on the way of finding what java bean is.
  • What is a Java Bean
Simple answer for that is Java Bean is also a normal java class. But all java classes are not java beans.
To be a Java Bean classes should have following,
  1. All properties of the class should be private. Getters and setters can be used to get and set the elements.
  2. Class should has a public but no-argument constructor.
  3. Java Serializable interface should be implemented.
So if those things have in a java class we can call it as a Java Bean. So it is a standard 
People use Word java bean to recognize java classes which are built in a predefined way.

  • Could you give me an example
Here is an example java bean

public class Employee implements java.io.Serializable{  

private int id;  
private String name; 
private String address;
private int age;
  
public Employee(){}  
  
public void setId(int id){this.id=id;}  
  
public int getId(){return id;}  
  
public void setName(String name){this.name=name;}  
  
public String getName(){return name;}  

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

public int getAge(){return age;}
  
}  

Look whether this has all the features mentioned above. YES. so this is a java bean

Note: Remember,  we talked about normal java beans. there is whole different thing named EJB (enterprise java bean). names are similar. but don't be mixed with plain java beans and Enterprise java beans.

No comments:

Post a Comment

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...