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

ChatGPT Free Online Download the ChatGPT App Easily

Have you ever wanted to talk to a friendly, smart robot that helps you with…

5 days ago

Free GPT Chat? DeepSeek AI Does It Better

DeepSeek AI is becoming a friendly and powerful new tool in the world of artificial…

2 weeks ago

Spring Boot MySQL Complete CRUD REST API [ Free Sourecode ]

Do you want to become an expert in Spring Boot CRUD operations? This comprehensive tutorial…

3 weeks ago

CREATE Responsive Navigation Bar with FlexBox CSS!

Modern websites must have a navigation bar that is clear and responsive. FlexBox CSS is…

4 weeks ago

Registration with image upload Java Jdbc(Download Source code)

Introduction In this section, we will guide you step by step in the development of an image upload registration system in Java using MySQL and JDBC. In the application, users register…

2 months ago

Touchable shop Pos system using Java

The Touchable Shop POS (Point of Sale) system is a sophisticated software solution developed using…

3 months ago