Java

Java Beans

A Java Bean is a reusable software component that follows a specific set of conventions. JavaBeans are widely used in enterprise applications, frameworks like Spring, and JavaServer Pages (JSP). This article explains JavaBeans, their properties, advantages, and how to create and use them effectively.

1. What is a Java Bean?

A Java Bean is a class that follows certain design patterns:
1.It should have a public no-argument constructor.
2.It should provide getter and setter methods to access private properties.
3.It should be serializable (implements Serializable interface).

Why Use JavaBeans?

  • Encapsulation
  • Reusability
  • Framework Compatibility

2. Creating a Java Bean

Let’s create a simple Java Bean class named PersonBean:

import java.io.Serializable;

public class PersonBean implements Serializable {
    private String name;
    private int age;

    // No-argument constructor
    public PersonBean() {}

    // Getter and Setter methods
    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

Encapsulation: Private fields (name and age) with public getter/setter methods.
1. No-arg Constructor: Ensures proper instantiation.
2. Implements Serializable: Enables JavaBean to be saved/transferred over networks.

3. Using a Java Bean

Once the PersonBean is created, we can use it in our application:

public class Main {
    public static void main(String[] args) {
        // Creating an instance of PersonBean
        PersonBean person = new PersonBean();

        // Setting values
        person.setName("John Doe");
        person.setAge(30);

        // Getting values
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());
    }
}

 

 

 

admin

Recent Posts

Build Simple Water System Calculator in Java Using Swing

If you're just beginning to learn Java GUI programming creating an Water System Calculator is a fantastic project for…

1 week ago

GitHub Copilot vs Microsoft Copilot Best AI Tool to Use in 2025

GitHub is a powerful tool used by teams and developers around the globe. This guide is…

2 weeks ago

Chat with Claude AI Free – Your Super-Smart AI Buddy

It's like having a super-smart buddy that is always there to help you write stories,…

2 weeks ago

Best Festivals UK 2025 [Free Guide Included]

The UK is known for its rich history, diverse culture, and most of all  its…

3 weeks ago

Bank Holidays 2025 UK – Plan Your Perfect Long Weekends

Do you have a plan for your next holiday? Being aware of the Bank Holidays within the…

3 weeks ago

Master Cursor AI Full Guide for Students & Creators

The world is rapidly changing of software development AI-assisted tools for coding have become the main focus. As…

3 weeks ago