Packages: Module-3 Annotations & Java Beans 16MCA41
Packages: Module-3 Annotations & Java Beans 16MCA41
Packages: Module-3 Annotations & Java Beans 16MCA41
Module 3
Creating Packages, Interfaces, JAR files and Annotations. The core java API package, New java.Lang Sub
package, Built-in Annotations with examples. Working with Java Beans. Introspection, Customizers,
creating java bean, manifest file, Bean Jar file, new bean, adding controls, Bean properties, Simple
properties, Design Pattern events, creating bound properties, Bean Methods, Bean an Icon, Bean info class,
Persistence, Java Beans API.
package mypack;
public class employee
{
statement;
}
The above statement will create a package with name mypack in the project directory.
Java uses file system directories to store packages. For example, the .java file for any class
you define to be part of mypack package must be stored in a directory called mypack.
A package is always defined as a separate folder having the same name as the package
name
Store all the classes in that package folder.
All classes of the package which we wish to access outside the package must be declared
public.
All classes within the package must have the package statement as its first line
All classes of the package must be compiled before use (So that they are error free)
Example
//save as FirstProgram.java
package learnjava;
public class FirstProgram{
public static void main(String args[]) {
System.out.println("Welcome to package");
}
}
o The -d switch specifies the destination where to put the generated class file.
o If you want to keep the package within the same directory, you can use . (dot).
Importing a package
o import keyword is used to import built-in and user-defined packages into your java
source file so that your class can refer to a class that is in another package by
directly using its name.
o The import keyword is used to make the classes and interface of another package
accessible to the current package.
o If you import packagename.classname then only the class with
name classname in the package with name packagename will be available for use.
//save by A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.A;
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}
o If you use packagename.*, then all the classes and interfaces of this package
will be accessible but the classes and interface inside the subpackages will not be
available for use.
//save by First.java
package learnjava;
public class First{
public void msg() {
System.out.println("Hello");
}
}
//save by Second.java
import learnjava.*;
class Second {
public static void main(String args[]) {
First obj = new First();
obj.msg();
}
}
package package.subpackage;
3.2 Interfaces
Interface is a pure abstract class.They are syntactically similar to classes, but you cannot
create instance of an Interface and their methods are declared without any body.
Interface is used to achieve complete abstraction in Java.
When you create an interface it defines what a class can do without saying anything about
how the class will do it.
Syntax:
interface interface_name { }
Example
interface Moveable
{
int AVERAGE-SPEED=40;
void move();
}
Note
o Complier automatically converts methods of interface as public and abstract, and
the data member as public, static and final by default.
o Methods inside Interface must not be static, final.
o All variables declared inside interface are implicitly public static final
variables(constants).
o All methods declared inside Java Interfaces are implicitly public and abstract,
even if you don't use public or abstract keyword.
o Interface can extend one or more other interface.
o Interface cannot implement a class.
o Interface can be nested inside another interface.
interface Moveable
{
int AVG-SPEED = 40;
void move();
}
Output:
Average speed is 40
boolean isRollable()
{
return true;
}
public static void main(String args[])
{
Tyre tr=new Tyre();
System.out.println(tr.isMoveable());
System.out.println(tr.isRollable());
}
}
Output:
true
true
3.3JAR files
The Java Archive (JAR) file format enables you to bundle multiple files into a single
archive file.
Typically a JAR file contains
o the class files
o auxiliary resources (applets, images, audio)
An archive file is a file that is composed of one or more computer files along with
metadata.
Archive files are used to collect multiple data files together into a single file for easier
portability and storage.
It can be digitally sign the jar file to prove their origin.
Options
c: create a JAR file
f: output jar file
v: produce verbose output
jar-file: the name of the resulting JAR file
o can use any filename for a JAR file
o by convention, JAR filenames are given a .jar extension
input-file(s): a space-separated list of one or more files to be placed in the JAR file.
can contain the wildcard * symbol
can be directory names; directories are added recursively
Options
Options
Unpacking all the files in a JAR file will create directory structure
Example:
C:\jar xf pack.jar
To perform basic tasks with JAR files, you use the Java Archive Tool provided as part of the
Java Development Kit (JDK).
Operation Command
To create a JAR file jar cf jar-file input-file(s)
To view the contents of a JAR file jar tf jar-file
To extract the contents of a JAR file jar xf jar-file
To extract specific files from a JAR file jar xf jar-file archived-file(s)
3.4Annotations
Java annotations is a tag that represents metadata.
i.e. attached with class, interface, methods or fields to indicate some additional information
which can be used by java compiler and JVM.
Java annotations were added to Java from Java 5.
Annotations start with ‘@’
Multivalued Annotation
o These annotations consist of multiple data members/ name, value, pairs.
o Example: - @WebServlet(attribute1 =value1, atrribute2=value2,
attribute3=value3)
@Deprecated Annotation
o It is a marker annotation. It indicates that a declaration is obsolete and has been
replaced by a newer form.
o The Javadoc @deprecated tag should be used when an element has been
deprecated
o @deprecated tag is for documentation and @Deprecated annotation is for runtime
reflection.
o Example:
Output:
Deprecatedtest display()
@Override
o It is a marker annotation that can be used only on methods.
o A method annotated with @Override must override a method from a superclass.
o It is used to ensure that a superclass method is actually overridden, and not simply
overloaded.
class Animal{
void eatSomething(){
System.out.println("eating something");
}
}
class TestAnnotation1 {
public static void main(String args[]){
Animal a=new Dog();
a.eatSomething();
}
}
Output:
eating foods
@SuppressWarnings
o It is used to inform the compiler to suppress specified compiler warnings
o The warnings to suppress are specified by name, in string form. This type of
annotation can be applied to any type of declaration.
o Java groups warnings under two categories. They
are deprecation and unchecked.. Any unchecked warning is generated when a
legacy code interfaces with a code that use generics.
import java.util.*;
class TestAnnotation2{
@SuppressWarnings("unchecked")
public static void main(String args[]){
ArrayList list=new ArrayList();
list.add("anil");
list.add("vimal");
list.add("ratan");
for(Object obj:list)
System.out.println(obj);
}}
Output:
anil
vimal
ratan
@Retention Annotation
o It determines where and how long the annotation is retent.
o The 3 values that the @Retention annotation can have:
SOURCE: Annotations will be retained at the source level and ignored by
the compiler.
CLASS: Annotations will be retained at compile time and ignored by the
JVM.
RUNTIME: These will be retained at runtime.
@Documented
o It is a marker interface that tells a tool that an annotation is to be documented.
o It is designed to be used only as an annotation to an annotation declaration
@Target
o It is designed to be used only as an annotation to another annotation.
o @Target takes one argument, which must be constant from
the ElementType enumeration.
o This argument specifies the type of declarations to which the annotation can be
applied.
o The constants are shown below along with the type of declaration to which they
correspond.
Target Constant Annotations Can be applied for
ANNOTATION_TYPE Another annotation
CONSTRUCTOR Constructor
FIELD Field
LOCAL_VARIABLE Local Variable
METHOD Method
PACKAGE Package
PARAMETER Parameter
TYPE Class, Interface, or enumeration
@Inherited
o @Inherited is a marker annotation that can be used only on annotation declaration.
o It affects only annotations that will be used on class declarations.
o @Inherited causes the annotation for a superclass to be inherited by a subclass.
o Therefore, when a request for a specific annotation is made to the subclass, if that
annotation is not present in the subclass, then its superclass is checked. If that
[Access Specifier]@interface<AnnotationName>
{
DataType <Method Name>() [default value];
}
AnnotationName is an identifier.
Parameter should not be associated with method declarations and throws clause should not
be used with method declaration.
Parameters will not have a null value but can have a default value.
default value is optional.
Return type of method should be either primitive, enum, string, class name or array of
primitive, enum, string or class name type.
Characteristics
o It provides a default, no-argument constructor.
o It should be serializable and implement the java.io.Serializable interface.
o It may have a number of "getter" and "setter" methods for the properties.
o Class must not define any public instance variables.
Advantages
o A Bean obtains all the benefits of Java’s “write-once, run-anywhere” paradigm.
o The properties, events, and methods of a Bean that are exposed to another
application can be controlled.
o The configuration settings of a Bean can be saved in persistent storage and restored
at a later time.
o A Bean may register to receive events from other objects and can generate events
that are sent to other objects
Introspection
Introspection can be defined as the technique of obtaining information about bean
properties, events and methods.
Basically introspection means analysis of bean capabilities.
Beans support introspection in two ways:
o By adhering to specific rules, known as design patterns, when naming bean
features.
o By explicitly providing property, method, and event information with a related bean
information class.
Properties
A property is a subset of a Bean’s state.
A bean property is a named attribute of a bean that can affect its behavior or appearance.
Examples of bean properties include color, label, font, font size, and display size.
Types of JavaBeans Properties
o Simple properties
o Indexed properties
o Bound properties
o Constraints properties
Simple properties
A bean property refers to private variables with a single value whose changes are
independent of changes in any other property.
Simple properties are retrieved and specified using get and set methods respectively.
A read/write property has both of these methods to access its values.
The get method used to read the value of the property. The set method that sets the value
of the property.
The setXXX() and getXXX() methods are the heart of the java beans properties mechanism.
This is also called getters and setters.
Syntax:
Example:
Indexed Properties
A bean property that supports a range of values instead of a single value.
Indexed Properties are consists of multiple values.
If a simple property can hold an array of value they are no longer called simple but instead
indexed properties.
Syntax:
public int[] get()
public property_datatype get(int index)
Example:
private double data[];
public double getData(int index)
{return data[index];}
Bound Properties
A bean property for which a change to the property results in a notification being sent to
some other bean.
Bound Properties are the properties of a JavaBean that inform its listeners about changes
in its values.
Bound Properties are implemented using the PropertyChangeSupport class and its
methods.
Constraint Properties
It generates an event when an attempt is made to change it value.
Constrained Properties are implemented using the PropertyChangeEvent class.
The event is sent to objects that previously registered an interest in receiving an such
notification.
A bean property for which a change to the property results in validation by another bean.
The other bean may reject the change if it is not appropriate.
Persistence
Persistence enables beans to save and restore their state through object serialization.
Object serialization means converting an object into a data stream and writing it to storage.
Persistence means an ability to save properties and events of our beans to non-volatile
storage and retrieve later.
It has the ability to save a bean to storage and retrieve it at a later time configuration settings
are saved It is implemented by Java serialization.
Customizers
Customization provides a means for modifying the appearance and behavior of a bean
within an application builder so it meets your specific needs.
There are several levels of customization available for a bean developer to allow other
developers to get maximum benefit from a bean's potential functionality.
A bean's appearance and behavior can be customized at design time within beans-
compliant builder tools. There are two ways to customize a bean:
o By using a property editor. Each bean property has its own property editor. The
NetBeans GUI Builder usually displays a bean's property editors in the Properties
window. The property editor that is associated with a particular property type edits
that property type.
o By using customizers. Customizers give you complete GUI control over bean
customization. Customizers are used where property editors are not practical or
Manifest file
The manifest file for a JavaBean application contains a list of all the class files that make
up a JavaBean
The entry in the manifest file enables the target application to recognize the JavaBean
classes for an application
For example, the entry for the MyBean JavaBean in the manifest file is as shown:
Manifest-Version: 1.0
Name: MyBean.class
Java-Bean: true
Note: write that 2 lines code in the notepad and save that file as MyBean.mf
Bean an Icon
A bean implementor who wishes to provide explicit information about their bean may
provide a BeanInfo class that implements this BeanInfo interface and provides explicit
information about the methods, properties, events, etc, of their bean.
Interface Summary
AppletInitializer This interface is designed to work in collusion with
java.beans.Beans.instantiate.
BeanInfo A bean implementor who wishes to provide explicit information
about their bean may provide a BeanInfo class that implements
this BeanInfo interface and provides explicit information about
the methods, properties, events, etc, of their bean.
Customizer A customizer class provides a complete custom GUI for
customizing a target Java Bean.
PropertyChangeListener A "PropertyChange" event gets fired whenever a bean changes a
"bound" property
PropertyEditor A PropertyEditor class provides support for GUIs that want to
allow users to edit a property value of a given type.
Class summary
BeanDescriptor A BeanDescriptor provides global information about a "bean",
including its Java class, its displayName, etc.
Beans This class provides some general purpose beans control methods