Creating a JavaBean Class

Introduction

A JavaBean class has a simple layout that includes a property(ies) and an accessor method (get()) and a mutator method (set()) to manipulate the value(s) of the property(ies).

A Basic Structure of a JavaBean Class

public class SampleBean
{
private String name;

public void setName(String name)
{
this.name = name;
}

public String getName()
{
return name;
}
}

 

Syntax for Setter Method

  • The Setter Method should be public such that the user can mutate the property values.
  • Should have void return type.
  • The setter method must have set in the method name. For ex: setName(), setId(), etc.
  • The method must have an argument list. It should not be a no-arg method.

Syntax for Getter Methods

  • The Setter Method should be public such that the user can access the property values.
  • As we will be fetching data, the method must have a return type (not void return type).
  • The method should have get in the method name. For ex: getName(), getId(), etc.
  • Should not have an argument list.
  • If it is a boolean property, both get or is can be used as the method name but ‘is’ is preferred in such case.
    For Example:
public class Test
{
private boolean empty;

public boolean getName()
{
return empty;
}
public boolean isempty()
{
return empty;
}
}

 

Example

public class Student implements java.io.Serializable
{
private int id;
private String name;

 public Student()
{
}

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 class Test
{
public static void main(String args[])
{
//Creating an object of the Java Bean class
Student s = new Student();
//Setting value of the object
s.setName("Alex");
System.out.println(s.getName());
}
}

 

OUTPUT

Alex

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.