SlideShare a Scribd company logo
Java Beans
Shivasubramanian A
What is a Java Bean?
 Ensures that developers can
 Capture the state of a given entity
 Discover the state of a given entity
 Achieved by writing Java classes that follow
the JavaBean specification
 Belongs to the java.desktop module
 Two packages
 java.beans
 java.beans.context
When is a Java class a JavaBean?
 When the class follows the JavaBean spec
 The class should only contain getters and/or
setters.
 The class should not extend any other class or
interface.
 Getters returning boolean values must begin with
‘is’.
When is a Java class a JavaBean?
class Employee {
private Integer age;
public void getAge() { return this.age; }
public void setAge(Integer age) {
this.age = age;
}
}
Java Bean properties
 Any aspect of a Java Bean available via
getter/setter methods is called a “Java bean
property”.
Java Bean properties
class Employee {
private Integer age;
public void getAge() { return this.age; }
public void setAge(Integer age) {
this.age = age;
}
public void isValidAge() {
return age <= 100 && age >= 0;
}
}
Properties – age, validAge
Java Bean properties
Read-only properties – only getter method
Write-only properties – only setter method
Read/write properties – getter & setter
Types of Java Bean properties
Indexed properties
Bound properties
Constrained properties
Indexed properties
Basically arrays
 Getters return array
 Setters take in an array
Must provide getter/setter for each element of
the property
Indexed properties...
Student.java
public class Student {
private String name;
private String[] subjects = new String[] { “Maths”,
“Science”, “Geography”};
public void getSubjects { return this.subjects;}
public void setSubjects(String[] sub) { this.subjects =
sub; }
public void getSubject(int index) { return
this.subjects[index]; }
public void setSubject(int index, String subject) {
this.subjects[index] = subject; }
}
Indexed properties...
Main.java
public class Main {
public static void main(String args[]) {
Student student = new Student();
student.getSubject(2); //returns “Geography”
student.setSubject(2, “Civics”);
student.getSubject(2); //returns “Civics”
}
}
Bound properties
Java bean which has listeners
 Changes to the bean triggers the listeners
You have to write code to:
 Add/remove listeners
 Notify listeners
You can have listeners for
 All properties
 Specific properties
Bound properties -
Add/remove listeners
java.beans.PropertyChangeSupport
 Provides methods to maintain a list of
listeners
 Provides methods to notify listeners of
changes
Bound properties -
Add/remove listeners
Student.java
public class Student {
private String name;
private int[] marks = new int[3];
private int total;
//getters & setters
PropertyChangeSupport pcs = new
PropertyChangeSupport(this);
public void addPropertyListener(PropertyChangeListener pcl)
{
this.pcs.addPropertyChangeListener(pcl);
}
//remove property listener
Bound properties –
Notify listeners
To notify listeners, use methods
 PropertyChangeSupport.firePropert
yChange
 PropertyChangeSupport.fireIndexed
PropertyChange
Bound properties –
Notify listeners
Student.java
public class Student {
private String name;
private int[] marks = new int[3];
private int total;
//add/remove property listener
PropertyChangeSupport pcs = new
PropertyChangeSupport(this);
public void setMarks(int[] marks) {
this.marks = marks;
int oldTotal = total;
this.total = sum(marks);
pcs.firePropertyChange(“total”, oldTotal, this.total);
Bound properties – listener code
Listener classes
 Implements PropertyChangeListener
 Single method,
propertyChange(PropertyChangeEven
t evt)
Bound properties – listener code
StudentRanker.java
public class StudentRanker implements PropertyChangeListener {
private List<Student> studentsRanking = new ArrayList<>();
public void propertyChange(PropertyChangeEvent evt) {
Student source = (Student) evt.getSource();
studentsRanking.add(source);
studentsRanking.sort(studentsTotalComparator);
}
}
Constrained properties
Bound properties that have veto power over
the new value being set
 Throw
java.beans.PropertyVetoException
to veto
You have to write code to:
 Add/remove listeners
 Notify listeners
You can have listeners for
Constrained properties -
Add/remove listeners
java.beans.VetoableChangeSupport
 Provides methods to maintain a list of
listeners
 Provides methods to notify listeners of
changes
Constrained properties -
Add/remove listeners
Student.java
public class Student {
private String name;
private int[] marks = new int[3];
private int total;
//getters & setters
VetoableChangeSupport vcs = new
VetoableChangeSupport(this);
public void
addVetoableChangeListener(VetoableChangeListener pcl) {
this.vcs.addVetoableChangeListener(pcl);
}
//remove vetoable change listener
Constrained properties –
Notify listeners
To notify listeners, use methods
 PropertyChangeSupport.fireVetoabl
eChange
Constrained properties –
Notify listeners
Student.java
public class Student {
private String name;
private int[] marks = new int[3];
private int total;
//add/remove property listener
VetoableChangeSupport vcs = new
VetoableChangeSupport(this);
public void setMarks(int[] marks) {
vcs.fireVetoableChange(“marks”, this.marks, marks);
this.marks = marks;
int oldTotal = total;
this.total = sum(marks);
Constrained properties – listener
code
Listener classes
 Implements VetoableChangeListener
 Single method,
vetoableChange(PropertyChangeEven
t evt)
Constrained properties – listener
code
MarksValidator.java
public class MarksValidator implements VetoableChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
int[] marks = (int[]) evt.getNewValue();
for (int mark : marks) {
if (mark < 0 || mark > 100) {
throw new PropertyVetoException(“Mark is
invalid.”, evt);
}
}
}
}
Bean methods
Any methods that don’t meet the JavaBean
spec are called bean methods
Long term bean persistence
Store a bean as an XML file
Useful for sharing state of beans
java.beans.XMLEncoder will convert the bean
into an XML file
java.beans.XMLDecoder will build the bean
from the XML file
Long term bean persistence
– XMLEncoder
Student.java
public class Student {
private String name;
private String[] subjectsTaken;
//getters & setters
}
Long term bean persistence
– XMLEncoder
StudentEncoder.java
Student student = new Student();
student.setName(“Student1”);
student.setSubjects(new String[] {“Maths”, “Physics”});
XMLEncoder encoder = new XMLEncoder(
new BufferedOutputStream(
new FileOutputStream(“Student.xml”)));
encoder.writeObject(student);
encoder.close();
Long term bean persistence
– XMLEncoder
Student.xml
<object class=”Student”>
<void property=”name”>
<string>Student1</string>
</void>
<void property=”subjectsTaken”>
<array class=”java.lang.String” length=”2”>
<void index=”0”>
<string>Maths</string>
</void>
<void index=”1”>
<string>Science</string>
Long term bean persistence
– XMLDecoder
StudentDecoder.java
XMLDecoder decoder = new XMLDecoder(
new BufferedInputStream(
new FileInputStream(“Student.xml”)));
Student student = (Student) decoder.getObject();

More Related Content

What's hot (20)

PDF
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
PPTX
Introduction to JPA (JPA version 2.0)
ejlp12
 
PPTX
Introduction to JPA Framework
Collaboration Technologies
 
PDF
Java Course 14: Beans, Applets, GUI
Anton Keks
 
PPT
Deployment
Roy Antony Arnold G
 
PDF
Introduction to JDBC and database access in web applications
Fulvio Corno
 
PDF
JPA and Hibernate
elliando dias
 
PPTX
Hibernate inheritance and relational mappings with examples
Er. Gaurav Kumar
 
PPT
jpa-hibernate-presentation
John Slick
 
PPT
EJB Clients
Roy Antony Arnold G
 
PPT
hibernate with JPA
Mohammad Faizan
 
PDF
Jdbc[1]
Fulvio Corno
 
PPTX
Hibernate
Prashant Kalkar
 
PPS
Dacj 4 2-c
Niit Care
 
PPTX
Spring (1)
Aneega
 
PPS
Dacj 4 2-b
Niit Care
 
PDF
Jpa
vantinhkhuc
 
PDF
13 java beans
snopteck
 
PPS
Packages and inbuilt classes of java
kamal kotecha
 
PPTX
Hibernate ppt
Aneega
 
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
Introduction to JPA (JPA version 2.0)
ejlp12
 
Introduction to JPA Framework
Collaboration Technologies
 
Java Course 14: Beans, Applets, GUI
Anton Keks
 
Introduction to JDBC and database access in web applications
Fulvio Corno
 
JPA and Hibernate
elliando dias
 
Hibernate inheritance and relational mappings with examples
Er. Gaurav Kumar
 
jpa-hibernate-presentation
John Slick
 
EJB Clients
Roy Antony Arnold G
 
hibernate with JPA
Mohammad Faizan
 
Jdbc[1]
Fulvio Corno
 
Hibernate
Prashant Kalkar
 
Dacj 4 2-c
Niit Care
 
Spring (1)
Aneega
 
Dacj 4 2-b
Niit Care
 
13 java beans
snopteck
 
Packages and inbuilt classes of java
kamal kotecha
 
Hibernate ppt
Aneega
 

Similar to Java beans (20)

PPT
Object Oriented JavaScript
Donald Sipe
 
PPSX
Observer design pattern
Sara Torkey
 
PPT
Java-Variables_about_different_Scope.ppt
JyothiAmpally
 
PDF
First java-server-faces-tutorial-en
techbed
 
PPTX
Computer programming 2 -lesson 4
MLG College of Learning, Inc
 
PPT
Bean Intro
vikram singh
 
PDF
Java beans
Ravi Kant Sahu
 
PDF
Object Oriented Programming in PHP
wahidullah mudaser
 
PDF
Lecture Notes
Dwight Sabio
 
PPTX
Effective java-3rd-edition-ch4
Matt
 
PPTX
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
SakkaravarthiS1
 
PPSX
Java session4
Jigarthacker
 
PDF
Access modifiers
Kasun Ranga Wijeweera
 
PPTX
OOPJ_PPT1, Inheritance, Encapsulation Polymorphism Static Variables.pptx
SrinivasGopalan2
 
PDF
Observer pattern
Somenath Mukhopadhyay
 
PDF
Object Oriented Programming using JAVA Notes
Uzair Salman
 
PPT
14. Defining Classes
Intro C# Book
 
PPT
Defining classes-and-objects-1.0
BG Java EE Course
 
PPTX
INHERITANCE.pptx
AteeqaKokab1
 
PDF
Demystifying Object-Oriented Programming #phpbnl18
Alena Holligan
 
Object Oriented JavaScript
Donald Sipe
 
Observer design pattern
Sara Torkey
 
Java-Variables_about_different_Scope.ppt
JyothiAmpally
 
First java-server-faces-tutorial-en
techbed
 
Computer programming 2 -lesson 4
MLG College of Learning, Inc
 
Bean Intro
vikram singh
 
Java beans
Ravi Kant Sahu
 
Object Oriented Programming in PHP
wahidullah mudaser
 
Lecture Notes
Dwight Sabio
 
Effective java-3rd-edition-ch4
Matt
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
SakkaravarthiS1
 
Java session4
Jigarthacker
 
Access modifiers
Kasun Ranga Wijeweera
 
OOPJ_PPT1, Inheritance, Encapsulation Polymorphism Static Variables.pptx
SrinivasGopalan2
 
Observer pattern
Somenath Mukhopadhyay
 
Object Oriented Programming using JAVA Notes
Uzair Salman
 
14. Defining Classes
Intro C# Book
 
Defining classes-and-objects-1.0
BG Java EE Course
 
INHERITANCE.pptx
AteeqaKokab1
 
Demystifying Object-Oriented Programming #phpbnl18
Alena Holligan
 
Ad

Recently uploaded (20)

PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Learn Computer Forensics, Second Edition
AnuraShantha7
 
PDF
July Patch Tuesday
Ivanti
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PPTX
Q2 Leading a Tableau User Group - Onboarding
lward7
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Learn Computer Forensics, Second Edition
AnuraShantha7
 
July Patch Tuesday
Ivanti
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Q2 Leading a Tableau User Group - Onboarding
lward7
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
Ad

Java beans

  • 2. What is a Java Bean?  Ensures that developers can  Capture the state of a given entity  Discover the state of a given entity  Achieved by writing Java classes that follow the JavaBean specification  Belongs to the java.desktop module  Two packages  java.beans  java.beans.context
  • 3. When is a Java class a JavaBean?  When the class follows the JavaBean spec  The class should only contain getters and/or setters.  The class should not extend any other class or interface.  Getters returning boolean values must begin with ‘is’.
  • 4. When is a Java class a JavaBean? class Employee { private Integer age; public void getAge() { return this.age; } public void setAge(Integer age) { this.age = age; } }
  • 5. Java Bean properties  Any aspect of a Java Bean available via getter/setter methods is called a “Java bean property”.
  • 6. Java Bean properties class Employee { private Integer age; public void getAge() { return this.age; } public void setAge(Integer age) { this.age = age; } public void isValidAge() { return age <= 100 && age >= 0; } } Properties – age, validAge
  • 7. Java Bean properties Read-only properties – only getter method Write-only properties – only setter method Read/write properties – getter & setter
  • 8. Types of Java Bean properties Indexed properties Bound properties Constrained properties
  • 9. Indexed properties Basically arrays  Getters return array  Setters take in an array Must provide getter/setter for each element of the property
  • 10. Indexed properties... Student.java public class Student { private String name; private String[] subjects = new String[] { “Maths”, “Science”, “Geography”}; public void getSubjects { return this.subjects;} public void setSubjects(String[] sub) { this.subjects = sub; } public void getSubject(int index) { return this.subjects[index]; } public void setSubject(int index, String subject) { this.subjects[index] = subject; } }
  • 11. Indexed properties... Main.java public class Main { public static void main(String args[]) { Student student = new Student(); student.getSubject(2); //returns “Geography” student.setSubject(2, “Civics”); student.getSubject(2); //returns “Civics” } }
  • 12. Bound properties Java bean which has listeners  Changes to the bean triggers the listeners You have to write code to:  Add/remove listeners  Notify listeners You can have listeners for  All properties  Specific properties
  • 13. Bound properties - Add/remove listeners java.beans.PropertyChangeSupport  Provides methods to maintain a list of listeners  Provides methods to notify listeners of changes
  • 14. Bound properties - Add/remove listeners Student.java public class Student { private String name; private int[] marks = new int[3]; private int total; //getters & setters PropertyChangeSupport pcs = new PropertyChangeSupport(this); public void addPropertyListener(PropertyChangeListener pcl) { this.pcs.addPropertyChangeListener(pcl); } //remove property listener
  • 15. Bound properties – Notify listeners To notify listeners, use methods  PropertyChangeSupport.firePropert yChange  PropertyChangeSupport.fireIndexed PropertyChange
  • 16. Bound properties – Notify listeners Student.java public class Student { private String name; private int[] marks = new int[3]; private int total; //add/remove property listener PropertyChangeSupport pcs = new PropertyChangeSupport(this); public void setMarks(int[] marks) { this.marks = marks; int oldTotal = total; this.total = sum(marks); pcs.firePropertyChange(“total”, oldTotal, this.total);
  • 17. Bound properties – listener code Listener classes  Implements PropertyChangeListener  Single method, propertyChange(PropertyChangeEven t evt)
  • 18. Bound properties – listener code StudentRanker.java public class StudentRanker implements PropertyChangeListener { private List<Student> studentsRanking = new ArrayList<>(); public void propertyChange(PropertyChangeEvent evt) { Student source = (Student) evt.getSource(); studentsRanking.add(source); studentsRanking.sort(studentsTotalComparator); } }
  • 19. Constrained properties Bound properties that have veto power over the new value being set  Throw java.beans.PropertyVetoException to veto You have to write code to:  Add/remove listeners  Notify listeners You can have listeners for
  • 20. Constrained properties - Add/remove listeners java.beans.VetoableChangeSupport  Provides methods to maintain a list of listeners  Provides methods to notify listeners of changes
  • 21. Constrained properties - Add/remove listeners Student.java public class Student { private String name; private int[] marks = new int[3]; private int total; //getters & setters VetoableChangeSupport vcs = new VetoableChangeSupport(this); public void addVetoableChangeListener(VetoableChangeListener pcl) { this.vcs.addVetoableChangeListener(pcl); } //remove vetoable change listener
  • 22. Constrained properties – Notify listeners To notify listeners, use methods  PropertyChangeSupport.fireVetoabl eChange
  • 23. Constrained properties – Notify listeners Student.java public class Student { private String name; private int[] marks = new int[3]; private int total; //add/remove property listener VetoableChangeSupport vcs = new VetoableChangeSupport(this); public void setMarks(int[] marks) { vcs.fireVetoableChange(“marks”, this.marks, marks); this.marks = marks; int oldTotal = total; this.total = sum(marks);
  • 24. Constrained properties – listener code Listener classes  Implements VetoableChangeListener  Single method, vetoableChange(PropertyChangeEven t evt)
  • 25. Constrained properties – listener code MarksValidator.java public class MarksValidator implements VetoableChangeListener { public void propertyChange(PropertyChangeEvent evt) { int[] marks = (int[]) evt.getNewValue(); for (int mark : marks) { if (mark < 0 || mark > 100) { throw new PropertyVetoException(“Mark is invalid.”, evt); } } } }
  • 26. Bean methods Any methods that don’t meet the JavaBean spec are called bean methods
  • 27. Long term bean persistence Store a bean as an XML file Useful for sharing state of beans java.beans.XMLEncoder will convert the bean into an XML file java.beans.XMLDecoder will build the bean from the XML file
  • 28. Long term bean persistence – XMLEncoder Student.java public class Student { private String name; private String[] subjectsTaken; //getters & setters }
  • 29. Long term bean persistence – XMLEncoder StudentEncoder.java Student student = new Student(); student.setName(“Student1”); student.setSubjects(new String[] {“Maths”, “Physics”}); XMLEncoder encoder = new XMLEncoder( new BufferedOutputStream( new FileOutputStream(“Student.xml”))); encoder.writeObject(student); encoder.close();
  • 30. Long term bean persistence – XMLEncoder Student.xml <object class=”Student”> <void property=”name”> <string>Student1</string> </void> <void property=”subjectsTaken”> <array class=”java.lang.String” length=”2”> <void index=”0”> <string>Maths</string> </void> <void index=”1”> <string>Science</string>
  • 31. Long term bean persistence – XMLDecoder StudentDecoder.java XMLDecoder decoder = new XMLDecoder( new BufferedInputStream( new FileInputStream(“Student.xml”))); Student student = (Student) decoder.getObject();