0% found this document useful (0 votes)
1 views122 pages

Javaunit1 New

Boxing in Java refers to the automatic conversion of primitive data types into their corresponding Wrapper types, while unboxing is the reverse process. Wrapper classes allow primitive types to be treated as objects, and features like autoboxing and auto-unboxing simplify code by eliminating the need for manual conversions. Additionally, annotations and enums in Java provide metadata capabilities and a way to define a group of constants, respectively.

Uploaded by

Nithin Nith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views122 pages

Javaunit1 New

Boxing in Java refers to the automatic conversion of primitive data types into their corresponding Wrapper types, while unboxing is the reverse process. Wrapper classes allow primitive types to be treated as objects, and features like autoboxing and auto-unboxing simplify code by eliminating the need for manual conversions. Additionally, annotations and enums in Java provide metadata capabilities and a way to define a group of constants, respectively.

Uploaded by

Nithin Nith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 122

What is boxing in java?

The automatic adaptation of


primitive data types into its
corresponding Wrapper type is
known as boxing, and reverse
operation is known as unboxing.
Since it is a new feature in Java; so Java
programmers do not need to write the
conversion code.
One advantage of using this feature is
that programmers do not require to
convert between primitives and
Wrappers manually and hence less
coding is needed.
What are Wrappers in Java?
Wrapper class in Java provides the
mechanism to convert primitive into
object and object into primitive.
A wrapper type/class of Java is one of 8
classes provided in the 'java.lang' The
package used for creating objects for the
eight primitive types.
Wrapper classes are
used to represent
primitive values when an
Object is required.
The
lists of all wrapper classes are:
short
byte
integer
long
float
double
boolean
character
What are Autoboxing and auto
unboxing???
Autoboxing is the process by which a
primitive type is automatically encapsulated
(boxed) into its equivalent type wrappers
whenever an object of the type is needed.
There is no need to construct an object
explicitly.
 Autoboxing is the process by which the
value of a boxed object is automatically
extracted (unboxed) from a type wrapper
when the program requires its value.
Furthermore, autoboxing and
auto-unboxing significantly
streamline the code of several
algorithms, removing the
tedium of manually boxing and
unboxing values.
With autoboxing, Java
programmers would be able to
make cleaner and faster codes
that are easier to read and
understand.
Java compilers simplify
programming and
automatically convert Wrapper
classes to primitive types and
vice versa.
Here is an example of the Wrapper
class and primitive types.
Wrapper class Primitive Data types
Float float
Integer int
Short short
Double double
Byte byte
Character char
Long long
Boolean boolean
Autoboxing and unboxing in
expressions
Whenever we use the object of Wrapper class in an
expression, automatic unboxing and boxing are done
by JVM.
Here is a simple code snippet showing the autoboxing
feature of Java:
Copy Code
Integer iOb;
iOb = 100; //Autoboxing of int
++iOb;
When programmers perform
incrementing of variables/objects of
type integers, automatic boxing and
unboxing are done by JVM,
where the object is first unboxed then
incremented and then again reboxed into
integer type object.
There are some benefits that this new
feature of Java provides us.
Less code to write
They are:
The code looks cleaner and easily readable
Programmers do not have to perform Explicit typecasting
The best method for conversion is automatically chosen
It helps prevent errors but may lead to unexpected results
sometimes
Annotations(meta data)
With JDK 5, another new facility was
provided that enables programmers to
embed supplemental information into a
source file.
This information is called an annotation
which does not change the action of a
program.
Thus annotation leaves the semantics of
any program unchanged.
Annotations allow developers to add metadata
information to source codes. Metadata is a set of
data that describes other data in the program.
 Annotations and metadata are not part of the
source code and would not be compiled.
 The use of annotations was first added in JDK 5
(Java Development Kit). Annotations do not have
a direct effect on the operation of the program.
Annotations in Java provide
additional information to the
compiler and JVM. An annotation
is a tag representing metadata
about classes, interfaces,
variables, methods, or fields.
Annotations do not impact the
execution of the code that they
annotate.
Some of the characteristics of
Begin with ‘@’
annotations

are:
Do not alter the execution of the program
Provide supplemental information and help to link
metadata with elements of a program such as classes,
variables, constructs, methods, etc.
Are different from comments since they can affect how
the program is treated by the compiler
// Java program to illustrate the Concept
// of Autoboxing and Unboxing // Print statements
System.out.println("Value of i:" + i);
// Importing required classes System.out.println("Value of i1: " +
import java.io.*; i1);

// Main class // Autoboxing of character


class GFG { Character gfg = 'a';

// Main driver method // Auto-unboxing of Character


public static void main(String[] args) char ch = gfg;
{
// Print statements
// Creating an Integer Object System.out.println("Value of ch: " +
// with custom value say it be 10 ch);
Integer i = new Integer(10); System.out.println(" Value of gfg: "
+ gfg);
// Unboxing the Object }
}
Categories of Annotations
Annotations can be categorized broadly into 5
categories:
Here is the declaration of
annotation named FirstAnno:

Example:
// A simple annotation type
@ interface FirstAnno{
String str();
int val();
}
The @ symbol preceding the keyword interface tells
the compiler that an annotation type is being declared.
There are also two members str() and val(). All
annotation solely consists of method declaration and
these methods act much like fields.
It is to be noted that annotation
cannot include extends clause.
However, it is automatic that all
annotation programs extend
the Annotation interface.
Thus Annotation is the superclass
of all annotations.
An enumeration is created using the enum keyword.
For example, here is a simple enumeration that lists
various apple varieties:
Enums
An enum is a special "class" that represents a group
of constants (unchangeable variables,
like final variables).
To create an enum, use the enum keyword (instead of
class or interface), and separate the constants with a
comma. Note that they should be in uppercase letters:
Example

// An enumeration of apple varieties. enum Apple


{ Jonathan, GoldenDel, RedDel, Winesap, Cortland }
EXAMPLE OF ENUM
enum Level
{
LOW,
MEDIUM,
HIGH
}
You can access enum constants with the dot syntax:
Eg:Level myVar = Level.MEDIUM;
Enum inside a Class
public class Main {
enum Level
{
LOW, MEDIUM, HIGH
}
public static void main(String[] args)
{
Level myVar = Level.MEDIUM; System.out.println(myVar);
}
}
The output will be:
MEDIUM
Difference between Enums and
Classes

An enum can, just like a class, have attributes and


methods.
The only difference is that enum constants
are public, static and final (unchangeable - cannot be
overridden).
An enum cannot be used to create objects, and it
cannot extend other classes (but it can implement
interfaces).
The identifiers Jonathan, GoldenDel, and so on, are
called enumeration constants.
Each is implicitly declared as a public, static final
member of Apple.
Furthermore, their type is the type of the enumeration
in which they are declared, which is Apple in this case.
Thus, in the language of Java, these constants are
called self-typed, in which “self” refers to the
enclosing enumeration
. Once you have defined an enumeration, you can
create a variable of that type.
However, even though enumerations define a class
type, you do not instantiate an enum using new.
 Instead, you declare and use an enumeration variable
in much the same way as you do one of the primitive
types.
.
For example,
this declares ap as a variable of enumeration type
Apple: Apple ap;
Because ap is of type Apple, the only values that it can
be assigned (or can contain) are those defined by the
enumeration
For example,
this assigns ap the value RedDel: ap = Apple.RedDel;
 Notice that the symbol RedDel is preceded by Apple.
Two enumeration constants can be compared for equality
by using the = = relational operator.
For example, this statement compares the value in ap
with the GoldenDel constant: if(ap ==
Apple.GoldenDel) // ...
// An enumeration of apple varieties.
enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
class EnumDemo {
public static void main(String args[]) {
Apple ap; ap = Apple.RedDel; // Output an enum value.
System.out.println("Value of ap: " + ap); System.out.println();
ap = Apple.GoldenDel; // Compare two enum values.
if(ap == Apple.GoldenDel) System.out.println("ap contains
GoldenDel.\n");
// Use an enum to control a switch statement.
switch(ap) {
case Jonathan: System.out.println("Jonathan is red.");
break;
case GoldenDel: System.out.println("Golden Delicious is yellow.");
break;
case RedDel: System.out.println("Red Delicious is red.");
break;
case Winesap: System.out.println("Winesap is red.");
break;
case Cortland: System.out.println("Cortland is red.");
break;
}
}
}
The output from the program is shown here:
Value of ap: RedDel
ap contains GoldenDel.
Golden Delicious is yellow.
The values( ) and valueOf( ) Methods
All enumerations automatically contain
two predefined methods: values( ) and
valueOf( ).
 Their general forms are shown here:
public static enum-type[ ] values( )
 public static enum-type valueOf(String
str)
The values( ) method returns an array
that contains a list of the enumeration
constants.
The valueOf( ) method returns the
enumeration constant whose value
corresponds to the string passed in str.
 In both cases, enum-type is the type of
the enumeration.
The following program demonstrates the
values( ) and valueOf( ) methods:
// Use the built-in enumeration methods.
// An enumeration of apple varieties.
enum Apple { Jonathan, GoldenDel, RedDel,
Winesap, Cortland
}
class EnumDemo2 {
public static void main(String args[]) {
Apple ap; System.out.println("Here are all Apple
constants:");
// use values()
Apple allapples[] = Apple.values();
for(Apple a : allapples)
System.out.println(a);
System.out.println(); // use valueOf()
ap = Apple.valueOf("Winesap");
System.out.println("ap contains " + ap);
}
}
The output from the program is shown here:
Here are all Apple constants:
Jonathan
GoldenDel
RedDel
Winesap
Cortland ap contains Winesap
Java Enumerations Are Class Types
a Java enumeration is a class type.
Although you don’t instantiate an
enum using new, it otherwise has
much the same capabilities as other
classes.
The fact that enum defines a class
gives powers to the Java enumeration
that enumerations in other languages
simply do not have.
For example, you can give them
constructors, add instance variables
and methods, and even implement
interfaces.
It is important to understand that
each enumeration constant is an object
of its enumeration type.
Thus, when you define a constructor
for an enum, the constructor is called
when each enumeration constant is
created.
 Also, each enumeration constant has
its own copy of any instance
variables defined by the enumeration.
Enum Class in Java
In Java, enum types are considered to be a
special type of class.
 It was introduced with the release of Java
5.
An enum class can include methods and
fields just like regular classes.
enum Size { constant1, constant2, …,
constantN;
// methods and fields
}
When we create an enum class,
the compiler will create
instances (objects) of each enum
constants.
Also, all enum constant is
always public static final by
default.
 Example 3: Java Enum Class case EXTRALARGE:
enum Size{ return "extra large";
SMALL, MEDIUM, LARGE,
EXTRALARGE; default:
return null;
public String getSize() { }
}
// this will refer to the object
SMALL public static void main(String[] args)
switch(this) { {
case SMALL:
return "small"; // call getSize()
// using the object SMALL
case MEDIUM: System.out.println("The size of the
return "medium"; pizza is " + Size.SMALL.getSize());
}
case LARGE: }
return "large";
output
The size of the pizza is small
In the above example, we have created an
enum class Size. It has four
constants SMALL, MEDIUM, LARGE and E
XTRALARGE.
Since Size is an enum class, the compiler
automatically creates instances for each enum
constants.
Here inside the main() method, we have used
the instance SMALL to call
the getSize() method.
Wrapper Classes in Java
A Wrapper class in Java is one whose
object wraps or contains primitive data
types.
Wrapper classes provide a way to use
primitive data types (int, boolean, etc..) as
objects.
When we create an object to a wrapper
class, it contains a field and in this field,
we can store primitive data types.
In other words, we can wrap a primitive
value into a wrapper class object.
ArrayList<int> myNumbers = new
ArrayList<int>();
// Invalid

// Valid
ArrayList<Integer> myNumbers =
new ArrayList<Integer>();
To create a wrapper object, use the wrapper class instead of the
primitive type.
To get the value, you can just print the object:
Example
public class Main
{
public static void main(String[] args)
{
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}
Need of Wrapper Classes
There are certain needs for using the
Wrapper class in Java as mentioned
below:
They convert primitive data types into
objects.
Objects are needed if we wish to
modify the arguments passed into a
method (because primitive types are
passed by value).
The classes in java.util package
handle only objects and hence wrapper
classes help in this case.
Data structures in the Collection
framework, such as ArrayList and
Vector, store only objects (reference
types) and not primitive types.
An object is needed to support
synchronization in multithreading.
Advantages of Wrapper Classes
Collections allow only object data.
On object data we can call multiple
methods compareTo(), equals(),
toString()
The cloning process only works on
objects
Object data allows null values.
Serialization allows only object data.
Since you're now working with objects, you
can use certain methods to get information
about the specific object.
For example, the following methods are
used to get the value associated with the
corresponding wrapper
object: intValue(), byteValue(), shortValue(),
longValue(), floatValue(), doubleValue(), ch
arValue(), booleanValue().
This example will output the same result as the
example above:
Example
public class Main {
public static void main(String[] args) { Integer
myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt.intValue());
System.out.println(myDouble.doubleValue());
System.out.println(myChar.charValue());
Autoboxing/Unboxing Occurs
in Expressions
In general, autoboxing and unboxing
take place whenever a conversion into
an object or from an object is required.
 This applies to expressions.
Within an expression, a numeric object
is automatically unboxed.
The outcome of the expression is
reboxed, if necessary.
AutoBoxing and Auto-UnBoxing occurs in
expressions. Lets understand it in the below
example -

Example -

Integer obj1=100, obj2 = 50, obj3;

obj3 = obj1 + obj2; //Here obj1 and obj2 are


auto-unboxed first, added and then autoboxed to
obj3
Java Autoboxing - Primitive Type to
Wrapper Object
In autoboxing, the Java compiler
automatically converts primitive types into
their corresponding wrapper class objects.
 For example,
int a = 56;
//autoboxing
Integer aObj = a;
Autoboxing has a great advantage while
working with Java collections.
In unboxing, the Java compiler
automatically converts wrapper class
objects into their corresponding primitive
types.
For example,
// autoboxing
Integer aObj = 56;
// unboxing
int a = aObj;
Like autoboxing, unboxing can also be used
with Java collections.
import java.util.ArrayList;
class Main
{
public static void main(String[] args)
{ ArrayList<Integer> list = new ArrayList<>();
//autoboxing
list.add(5);
list.add(6);
System.out.println("ArrayList: " + list);
// unboxing
int a = list.get(0);
System.out.println("Value at index 0: " + a); }
}
Benefits of Autoboxing / Unboxing
Autoboxing / Unboxing lets us use primitive
types and Wrapper class objects interchangeably.
We don't have to perform Explicit typecasting.
It helps prevent errors, but may lead to
unexpected results sometimes. Hence must be
used with care.
Auto-unboxing also allows you to mix different
types of numeric objects in an expression. When
the values are unboxed, the standard type
conversions can be applied.
Annotations
Annotations are used to provide
supplemental information about a
program.
Annotations start with ‘@’.
Annotations do not change the
action of a compiled program.
Annotations help to
associate metadata (information) to the
program elements i.e. instance variables,
constructors, methods, classes, etc.
Annotations are not pure comments as they
can change the way a program is treated by the
compiler. See below code for example.
Annotations basically are used to provide
additional information, so could be an
alternative to XML and Java marker interfaces.
Categories of Annotations
There are broadly 5 categories of
annotations as listed:
Marker Annotations
Single value Annotations
Full Annotations
Type Annotations
Repeating Annotations
Category 1: Marker Annotations
The only purpose is to mark a declaration. These
annotations contain no members and do not consist of
any data. Thus, its presence as an annotation is
sufficient. Since the marker interface contains no
members, simply determining whether it is present or
absent is sufficient. @Override is an example of
Marker Annotation.
Example
@TestAnnotation()
Category 2: Single value
Annotations

These annotations contain only one member and allow


a shorthand form of specifying the value of the
member. We only need to specify the value for that
member when the annotation is applied and don’t need
to specify the name of the member. However, in order
to use this shorthand, the name of the member must be
a value.
Example
@TestAnnotation(“testing”);
Category 3: Full Annotations

These annotations consist of multiple


data members, names, values, pairs.
Example
@TestAnnotation(owner=”Rahul”,
value=”Class Geeks”)
Category 4: Type Annotations
These annotations can be applied to any place where a
type is being used.
 For example, we can annotate the return type of a
method.
These are declared annotated
with @Target annotation.
Category 5: Repeating Annotations
These are the annotations that can be
applied to a single item more than once.
For an annotation to be repeatable it must
be annotated with
the @Repeatable annotation, which is
defined in
the java.lang.annotation package.
 Its value field specifies the container
type for the repeatable annotation.
The container is specified as an
annotation whose value field is an array
of the repeatable annotation type.
Hence, to create a repeatable annotation,
firstly the container annotation is created,
and then the annotation type is specified
as an argument to the @Repeatable
annotation.
Understanding Built-In Annotations
Let's understand the built-in annotations
first.
@Override
@Override annotation assures that the subclass
method is overriding the parent class method.
 If it is not so, compile time error occurs.
Sometimes, we does the silly mistake such as
spelling mistakes etc.
So, it is better to mark @Override annotation
that provides assurity that method is overridden.
class Animal{
void eatSomething(){
System.out.println("eating something");}
}

class Dog extends Animal{


@Override
void eatsomething(){System.out.println("eating foods");}//
should be eatSomething
}

class TestAnnotation1{
public static void main(String args[]){
Animal a=new Dog();
a.eatSomething();
}}
Test it NowOutput:
Specifying Retention Policy
In Java, annotations are used to attach meta-data
to a program element such as a class, method,
instances, etc.
Some annotations are used to annotate other
annotations. These types of annotations are
known as meta-annotations.
 @Retention is also a meta-annotation that
comes with some retention policies.
These retention policies determine at which
point an annotation is discarded.
There are three types of retention policies: SOURCE, CLASS,
and RUNTIME.
RetentionPolicy.SOURCE: The
annotations annotated using the SOURCE
retention policy are discarded at runtime.
RetentionPolicy.CLASS: The annotations
annotated using the CLASS retention policy
are recorded in the .class file but are
discarded during runtime.
 CLASS is the default retention policy in
Java.
RetentionPolicy.RUNTIME: The
annotations annotated using the
RUNTIME retention policy are
retained during runtime and can be
accessed in our program during
runtime.
What
 is JavaBeans?
JavaBeans is a portable, platform-
independent model written in Java
Programming Language.
Its components are referred to as beans.
In simple terms, JavaBeans are classes
which encapsulate several objects into a
single object.
 It helps in accessing these object from
multiple places.
JavaBeans contains several elements like
Constructors, Getter/Setter Methods and
much more.
What is Jsp?
JavaServer Pages (JSP) is a server-side
technology that creates dynamic web
applications.
 It allows developers to embed Java code
directly into HTML or XML pages and it
makes web development more efficient.
JSP is an advanced version of Servlets.
 It provides enhanced capabilities for
building scalable and platform-independent
web pages.
JSP simplifies web development by
combining the strengths of Java with
the flexibility of HTML. Some of the
advantages of JSP over Servlets are
listed below:
JSP code is easier to manage than
Servlets as it separates UI and business
logic.
JSP minimizes the amount of code
required for web applications.
Easily generates content dynamically
in response to user interactions.
It provides access to the complete
range of Java APIs for robust
application development.
JSP is suitable for applications with
growing user bases.
It is a software application on a
Java platform that is platform-
independent.
 It is portable, and its components
are called beans.
You can convert data structures or
objects into a particular format that
can be stored, transmitted, and
reconstructed later by the user,
which can be termed serialization
Uses of java beans
You can create and design any component.
As it is reusable software, one can use it in any
environment.
It contains different functions like spelling
correction and forecasting the stock market one
can perform several functions.
It also comes with a property of visible or
invisible.
The end-user can see it or maybe can’t see it. It
can work autonomously.
It is also capable of showing a pie chart.
JavaBeans has interactive capabilities that
can provide support to a web-based
application.
It is user-friendly and system-friendly also.
One can run JavaBeans on any operating
system.
One can run JavaBeans in several
applications like word processors,
browsers, and many more.
Instead of writing custom components, you
can use UI elements like graphical buttons,
trees, and many more.
While considering JavaBeans, you
must follow some conventions:

1. Several Conventions
A default constructor (no arguments) is a
must for JavaBeans.
Serialization(converting data into
bits/bytes)data can be transferred and
stored.
getter and setter methods(all variables
must be either private or protected)
2. Components
Components are the class that stores the
definition of beans.
Classes contain design conventions. It
includes persistence, events, properties, and
methods.
 It consists of two types of components i.e.,
Non-GUI and GUI.
3. Classes
Persistence: With the help of this class, you
can store the state of JavaBean.
Events: It is pretty alike to Swing event
handling.
Properties: It includes color, display, font,
etc. It will also show the appearance and
behavior of the bean and many more.
Methods: You will find it exactly like the
normal java methods.
4. Components
These components can be in the
following mode
write-only mode
read or write mode
read-only mode
Characteristics of Java Beans
Java Beans possess several key characteristics
that set them apart from regular Java classes.
These characteristics include:
Public Default Constructor: Java Beans must
have a public default constructor to allow the
framework or application to instantiate them.
Private Fields with Public
Accessors: Encapsulated fields within a Java
Bean should be declared as private, with
public getter and setter methods to access and
modify the data.
Serializable: Java Beans should
implement the Serializable interface,
enabling their state to be saved and
restored.
Event Support: Java Beans can
support events by implementing
appropriate listener interfaces, allowing
other components to be notified of state
changes.
Advantages of java beans
The best thing about Java beans is
that you have to write code only
once and can run anywhere.
You can work on several local
platforms.
The developer can control
properties, methods, and events.
At design time, a user can configure
JavaBeans without any disturbance.
It can easily be created. It is easy to
write JavaBean.
JavaBeans are light in weight. You don’t
have to make the extra effort to create a
suitable environment to support
JavaBean.
JavaBeans are compatible in nature.
JavaBeans are classes that encapsulate
many objects into a single object (the
bean).
 It is a Java class that should follow the
following conventions:
Must implement Serializable.
It should have a public no-arg
constructor.
All properties in java bean must be
private with public getters and setter
methods.
Below is the implementation of the
JavaBean Class:
// Java Program of JavaBean class // Getter for Id
package geeks; public int getId() { return id; }

public class Student implements // Setter for Name


java.io.Serializable { public void setName(String name)
private int id; { this.name = name; }
private String name;
// Getter for Name
// Constructor public String getName()
public Student() {} { return name;
}
// Setter for Id }
public void setId(int id) { this.id =
id; }
What is Introspection?
Introspection in JavaBeans refers to the
ability to examine and manipulate a
bean's properties, methods, and events at
runtime.
This dynamic behavior allows tools and
frameworks to work with JavaBeans without
prior knowledge of their structure.
Introspection is primarily used for tasks like
data binding, code generation, and
serialization.
Understanding introspection is crucial
for Java developers working with
JavaBeans, as it empowers them to
build flexible and reusable components
that can adapt to different runtime
scenarios.
 Whether you're developing GUI
applications, serialization frameworks,
or custom code generation tools,
introspection is a valuable tool in your
Java toolbox.
At the core of Java Beans
is introspection. This is the process of
analyzing a Bean to determine its
capabilities.
This is an essential feature of the Java
Beans API because it allows another
application, such as a design tool, to
obtain information about a component.
Without introspection, the Java Beans
technology could not operate.
Use Cases of Introspection
Introspection is a powerful feature in JavaBeans
and can be used in various scenarios, including:
Data Binding: Introspection allows mapping
user interface components to bean properties,
simplifying the process of transferring data
between the UI and beans.
Serialization: It enables tools to automatically
serialize and deserialize bean objects without
needing to know their structure in advance.
Code Generation: Code generation
tools can use introspection to generate
code for accessing bean properties and
invoking methods.
Customization: Frameworks and
containers can customize the behavior
of beans at runtime by introspecting
their properties and methods.
There are two ways in which the developer of
a Bean can indicate which of its properties,
events, and methods should be exposed.
With the first method, simple naming
conventions are used.
These allow the introspection mechanisms to
infer information about a Bean.
In the second way, an additional class that
extends the BeanInfo interface is provided that
explicitly supplies this information.
Design Patterns for Properties
A property is a subset of a Bean’s state.
The values assigned to the properties
determine the behavior and appearance of
that component.
A property is set through a setter method.
A property is obtained by
a getter method.
There are two types of properties: simple
and indexed.
Simple Properties
A simple property has a single value. It can be
identified by the following design patterns,
where N is the name of the property and T is its
type:
public T getN( ) public void setN(T arg)
A read/write property has both of these
methods to access its values.
A read-only property has only a get method.
A write-only property has only a set method.
Example of simple property

private double depth, height, width;

public double getDepth( ) {


return depth;

}
public void setDepth(double
d) { }
depth = d; public double getWidth( ) {
return width;
} }

public double getHeight( ) { public void


return height; setWidth(double w) {
width = w;
}
public void }
setHeight(double h) {
height = h;
Indexed Properties
An indexed property consists of multiple values.
It can be identified by the following design patterns,
where N is the name of the property and T is its type:
public T getN(int index);

public void setN(int index, T value); public T[ ] getN( );


public void setN(T values[ ]);

Here is an indexed property called data along with its


getter and setter methods:
private double data[ ];
public double getData(int index) {
return data[index];
}
public void setData(int index, double value) {
data[index] = value;
}
public double[ ] getData( ) {
return data;
}
public void setData(double[ ] values) {
data = new double[values.length];

System.arraycopy(values, 0, data, 0, values.length);


Bound Properties
Bound properties support the
PropertyChangeListener (in the API
reference documentation) class.
Sometimes when a Bean property changes,
another object might need to be notified of
the change, and react to the change.
Whenever a bound property changes,
notification of the change is sent to
interested listeners.
The accessor methods for a bound
property are defined in the same way as
those for simple properties.
However, you also need to provide the
event listener registration methods for
PropertyChangeListener classes and
fire a PropertyChangeEvent (in the API
reference documentation) event to
the PropertyChangeListener objects by
calling their propertyChange methods
the convenience PropertyChangeSupport
(in the API reference documentation)
class enables your bean to implement
these methods.
Your bean can inherit changes from
the PropertyChangeSupportclass, or use
it as an inner class.
In order to listen for property changes,
an object must be able to add and
remove itself from the listener list on
the bean containing the bound property.
 It must also be able to respond to the
event notification method that signals a
property change.
The PropertyChangeEvent class
encapsulates property change
information, and is sent from the
property change event source to each
object in the property change listener
list with the propertyChange method.
Implementing Bound Property
Support Within a Bean
To implement a bound property in your
application, follow these steps:
Import the java.beans package.
This gives you access to
the PropertyChangeSupport class.
Instantiate a PropertyChangeSupport object.
This object maintains the property change
listener list and fires property change events.
You can also make your class
a PropertyChangeSupport subclass.
Implement methods to maintain the
property change listener list.
Since a PropertyChangeSupport subclass
implements these methods, you merely
wrap calls to the property-change support
object's methods.
Modify a property's set method to fire a
property change event when the property is
changed.
Creating a Bound Property
Create the title property as a bound property
for the MyBean component in the NetBeans
GUI Builder, perform the following
sequence of operations:Right-click the Bean
Patterns node in the MyBean class hierarchy.
Select Add|Property from the pop-up menu.
Fill the New Property Pattern form as shown
on the following figure and click OK.
Note that the title property and the multicast event
source pattern PropertyChangeListener were added to
the Bean Patterns structure.
Constrained Properties
A bean property is constrained if the bean
supports the VetoableChangeListener(in the
API reference documentation) and
PropertyChangeEvent(in the API reference
documentation) classes, and if the set method
for this property throws a
PropertyVetoException(in the API reference
documentation).
Constrained properties are more complicated
than bound properties because they also
support property change listeners which
happen to be vetoers.
The following operations in
the setXXX method for the constrained
property must be implemented in this
order:
Save the old value in case the change
is vetoed.
Notify listeners of the new proposed
value, allowing them to veto the
change.
If no listener vetoes the change (no exception
is thrown), set the property to the new value.
The accessor methods for a constrained
property are defined in the same way as those
for simple properties, with the addition that
the setXXX method throws
a PropertyVetoException exception. The
syntax is as follows:
public void setPropertyName(PropertyType pt)
throws PropertyVetoException {
Code
}
Handling Vetoes
If a registered listener vetoes a proposed
property change by throwing
a PropertyVetoException exception, the
source bean with the constrained property is
responsible for the following
actions:Catching exceptions.
Reverting to the old value for the property.
Issuing a
new VetoableChangeListener.vetoableChang
e call to all listeners to report the reversion.
The VetoableChangeListener class throws
a PropertyVetoException and handles
the PropertyChangeEvent event fired by the bean with the
constrained property.
The VetoableChangeSupport provides the following
operations:
Keeping track of VetoableChangeListener objects.
Issuing the vetoableChange method on all registered
listeners.
Catching any vetoes (exceptions) thrown by listeners.
Informing all listeners of a veto by
calling vetoableChange again, but with the old property
value as the proposed "new" value.
Creating a Constrained Property
To create a constrained property, set the appropriate
option in the New Property Pattern form as shown on
the following figure.

You might also like