Java Beans - Notes by Shariq SP
Understanding Java Bean Class
A Java Bean is a reusable software component that follows specific conventions for its properties, methods, and events. Java Beans are commonly used in Java application development for encapsulating data and functionality.
To create a Java Bean class, you typically follow these conventions:
- Private member variables with public getter and setter methods for each variable.
- A public no-argument constructor.
- Implementing
Serializable
interface for supporting serialization.
Example 1: Java Bean Class
In this example, we have a simple Java Bean class Person
:
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;
public Person() {
// Default constructor
}
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;
}
}
Example 2: Java Bean Class
In this example, we have another Java Bean class Product
with more properties:
import java.io.Serializable;
public class Product implements Serializable {
private String name;
private double price;
private int quantity;
public Product() {
// Default constructor
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
Interview Questions on Java Bean
- What is a Java Bean?
- What are the conventions to create a Java Bean class?
- Why are getter and setter methods important in a Java Bean?
- What is the purpose of implementing the
Serializable
interface in a Java Bean? - Can a Java Bean class have methods other than getter and setter methods?
Multiple Choice Questions (MCQs) - Java Bean
- Which of the following is a convention for creating a Java Bean class?
- Public member variables
- Private member variables with public getter and setter methods
- No constructor
- No methods other than main method
- Why are getter and setter methods important in a Java Bean?
- To make member variables accessible from outside the class
- To encapsulate the behavior of the class
- To provide a default constructor
- To ensure thread safety
- What is the purpose of implementing the
Serializable
interface in a Java Bean?- To make the class immutable
- To allow the class instances to be serialized
- To ensure type safety
- To provide inheritance
- Can a Java Bean class have private getter and setter methods?
- Yes
- No
- Only if the class is final
- Only if the class is abstract
- What is the purpose of the default constructor in a Java Bean class?
- To initialize member variables with default values
- To ensure thread safety
- To restrict instantiation of the class
- To provide type safety