Java-Unit 2 Inheritance and Polymorphism
Java-Unit 2 Inheritance and Polymorphism
Unit-2
Inheritance and Polymorphism: Inheritance in java, Super and sub class, Overriding, Object
class, Polymorphism, Dynamic binding, Generic programming, Casting objects, Instance of operator,
Abstract class, Interface in java, Package in java, UTIL package.
Multithreading in java: Thread life cycle and methods, Runnable interface, Thread
synchronization, Exception handling with try catch-finally, Collections in java, Introduction to
JavaBeans and Network Programming.
INHERITANCE IN JAVA
INHERITANCE:EXTENDING A CLASS
Java does not directly implement multiple inheritance. However, this concept
is implemented using a secondary inheritance path in the form of interfaces.
Defining a subclass:
A sub class is defined as:
Class subclassname extends superclassname
variable declaration;
methods declaration;
The keyword extends signifies that the properties of the super classname are
extended to the subclassname. (or) The extends keyword indicates that you are
making a new class that derives from an existing class. The meaning of "extends"
is to increase the functionality. The subclass will now contain its own variables
and methods as well those of the superclass.This kind of situation occurs when we
want to add some more properties to an existing class without actually modifying
it.
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
System.out.println("weeping...");
}
SHWETHA RANI R S 1ST BCA Page 4
OBJECT ORIENTED PROGRAMMING WITH JAVA
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Hierarchical Inheritance
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow()
{
System.out.println("meowing...");
}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
The program defines a class room and extends it to another class bedroom. Note
that the class bedroom defines its own data members and methods.The sub class
bedroom now includes three instance variables, namely length, breadth and
height and two methods area and volume.
The constructor in the derived class uses the super keyword to pass values
SHWETHA RANI R S 1ST BCA Page 6
OBJECT ORIENTED PROGRAMMING WITH JAVA
calls first the bedroom constructor method, which in turn calls the room
constructor method by using the super keyword. Finally the object room1 of the
subclass bedroom calls the method area defines in the super class as well as the
method volume defined in the subclass itself.
Subclass constructor:
A subclass constructor is used to construct the instance variables of both the subclass
and the superclass.The subclass constructor uses the keyword super to invoke the
Constructor method of the superclass.This keyword super is used subject to the
following conditions:
• The call to super class constructor must appear as the first statement
within the subclass constructor.
• The parameters in the super call must match the order and type of the
instance variable declared in the super class.
OVERRIDING METHODS:
Defining a method in the subclass that has the same name, same arguments and same return
type as a method in the superclass. When the method is called, the method defined in the subclass is
invoked and executed instead of the one in the superclass.
(or)
However, there may be occasions when we want an object to respond to the same method but
have different behaviour when that method is called. That means, we should override the method
defined in the super class. This is possible by defining a method in the subclass that has the same name,
same arguments and same return type as a method in the super class. Then, when that method is called,
the method defined in the sub class is invoked and executed instead of the one in the superclass. This
is known as overriding
any type like Employee, Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject();
The Object class provides some common behaviors to all the objects such as object can be compared, object
can be cloned, object can be notified etc.
• toString() Method
• hashCode() Method
• equals(Object obj) Method
• getClass() method
• finalize() method
• clone() method
• wait(), notify() notifyAll() Methods
toString() Method:
It's provide string representation or convert object to string form. you can override toString() method
to get your own String representation of objects.
public String toString()
{
// Can override and give own definition
}
hashCode() Method:
It's generate unique hashcode for each object. The main advantage of saving objects. It's used to
override for user defined objects for better performance like searching.
equals(Object obj) Method:
It's used to compare the two objects dynamically.
getClass() Method:
It's return runtime class object and used to get metadata information as well.
finalize() method:
This method call required to perform garbage collector.
clone() method:
It used to create the copy or clone of object.
wait(), notify() notifyAll() Methods:
These are used in multithreading.
POLYMORPHISM IN JAVA
The word polymorphism means having many forms. In simple words, we can define polymorphism
as the ability of a message to be displayed in more than one form.
Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
Any Java object that can pass more than one IS-A test is considered to be polymorphic
A person at the same time can have different characteristics. Like a man at the same time is a father,
a husband, an employee. So the same person possesses different behavior in different situations. This
is called polymorphism.
Polymorphism is considered one of the important features of Object-Oriented Programming.
Polymorphism allows us to perform a single action in different ways. In other words, polymorphism
allows you to define one interface and have multiple implementations. The word “poly” means many
and “morphs” means forms, So it means many forms.
Types of polymorphism
• Compile-time Polymorphism
• Runtime Polymorphism
Method Overloading: When there are multiple functions with the same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded by change in
the number of arguments or/and a change in the type of arguments.
Example 1
// Java Program for Method overloading
// By using Different Types of Arguments
class Helper {
{
return a * b; // Returns product of integer numbers
}
// Method 2
{
return a * b; // Returns product of double numbers
}
}
// Class 2
// Main class
class GFG {
{
// Calling method by passing
// input as in arguments
System.out.println(Helper.Multiply(2, 4));
System.out.println(Helper.Multiply(5.5, 6.3));
}
}
Output:
8
34.65
Type 2: Runtime polymorphism
Casting objects
Upcasting and Downcasting in Java
A process of converting one data type to another is known
as Typecasting and Upcasting and Downcasting is the type of object typecasting. In Java, the
object can also be typecast like the datatypes. Parent and Child objects are two types of objects.
So, there are two types of typecasting possible for an object, i.e., Parent to Child and Child to
Parent or can say Upcasting and Downcasting.
Typecasting is used to ensure whether variables are correctly processed by a function or not.
In Upcasting and Downcasting, we typecast a child object to a parent object and a parent object
to a child object simultaneously. We can perform Upcasting implicitly or explicitly, but downcasting
cannot be implicitly possible.
1) Upcasting
Upcasting is a type of object typecasting in which a child object is typecasted to a parent class
object. By using the Upcasting, we can easily access the variables and methods of the parent class to
the child class. Here, we don't access all the variables and the method. We access only some specified
variables and methods of the child class. Upcasting is also known as Generalization and Widening.
UpcastingExample.java
class Parent{
void PrintData()
void PrintData()
}
SHWETHA RANI R S 1ST BCA Page 13
OBJECT ORIENTED PROGRAMMING WITH JAVA
class UpcastingExample
obj1.PrintData();
obj2.PrintData();
2) Downcasting
Upcasting is another type of object typecasting. In Upcasting, we assign a parent class reference object
to the child class. In Java, we cannot assign a parent class reference object to the child class, but if we
perform downcasting, we will not get any compile-time error. However, when we run it, it throws
the "ClassCastException". Now the point is if downcasting is not possible in Java, then why is it
allowed by the compiler? In Java, some scenarios allow us to perform downcasting. Here, the subclass
object is referred by the parent class.
Below is an example of downcasting in which both the valid and the invalid scenarios are explained:
DowncastingExample.java
//Parent class
class Parent {
String name;
void showMessage()
int age;
void showMessage()
p.name = "Shubham";
Child c = (Child)p;
c.age = 18;
System.out.println(c.name);
System.out.println(c.age);
c.showMessage();
GENERIC PROGRAMMING
The Java Generics programming is introduced to deal with type-safe objects. It makes the code
stable by detecting the bugs at compile time. Before generics, we can store any type of objects in the
collection, i.e., non-generic. Now generics force the java programmer to store a specific type of
objects.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-
defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to
create classes that work with different data types. An entity such as class, interface, or method that
operates on a parameterized type is a generic entity.
Why Generics?
The Object is the superclass of all other classes, and Object reference can refer to any object. These
features lack type safety. Generics add that type of safety feature. We will discuss that type of safety
feature in later examples
Types of Java Generics
Generic Method: Generic Java method takes a parameter and returns some value after performing a
task. It is exactly like a normal function, however, a generic method has type parameters that are
cited by actual type. This allows the generic method to be used in a more general way. The compiler
takes care of the type of safety which enables programmers to code easily since they do not have to
perform long, individual type castings.
Generic Classes: A generic class is implemented exactly like a non-generic class. The only
difference is that it contains a type parameter section. There can be more than one type of parameter,
separated by a comma. The classes, which accept one or more parameters, are known as
parameterized classes or parameterized types.
Generic Class
Like C++, we use <> to specify parameter types in generic class creation. To create objects of a
generic class, we use the following syntax.
// To create an instance of generic class
Test(T obj)
{
this.obj = obj; } // constructor
public T getObject()
{
return this.obj;
}
SHWETHA RANI R S 1ST BCA Page 16
OBJECT ORIENTED PROGRAMMING WITH JAVA
{
Test<Integer> iObj = new Test<Integer>(15); // instance of Integer type
System.out.println(iObj.getObject());
System.out.println(sObj.getObject());
}}
Output
15
BCA
Instance of operator
The java instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with any
variable that has null value, it returns false.
Simple example of java instanceof
Let's see the simple example of instance operator where it tests the current class.
class Simple1
{
public static void main(String args[])
{
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1); //true
}
}
Output:true
ABSTRAT CLASSES:
If the class acts as base class for many other classes and is not useful on its own, then we can
avoid instantiation and only it's declaration is enough. This is achieved by using abstract
keyword. Similarly we can have only method declaration and allow derived class to define it by
using abstract keyword. Such class is called abstract class and such method is called abstract
method. It can have abstract and non-abstract methods (method with the body).
We have seen that by making a method final we ensure that the method is not
redefined in a sub class. That is, the method can never be sub classed. Java allows us to
do something that is exactly opposite to this. That is, we can indicate that a method must
always be redefined in a sub class, thus making overriding compulsory. This is done using
the modifier keyword abstract in the method definition.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
Output:
running safely
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
When a class contains one or more abstract methods, it should also be declared
Abstract as shown in the example above.
INTERFACE IN JAVA
INTERFACES:MULTIPLE INHERITANCE
Java does not support multiple inheritance. That is, classes in Java cannot
have more than one superclass. For instance, a definition like:
.............................
.............................
Is not permitted in Java.a large number of real-life applications require the use of
multiple inheritance where by we inherit methods and properties from several
distinct classes.
DEFININGINTERFACES:
Interface interfacename
variable declaration;
methods declaration;
The syntax for defining an interface is very similar to that for defining a class.
Here, interface is the keyword and interfacename is any valid Java
variable(just like class names).
Note that all variables are declared as constants.
EXTENDINGINTERFACES
Body of name2
For example, we can put all the constants in one interface and the methods in the
Interface ItemConstants
Int code=1001 ;
String name=“Fan”;
Void display();
}
other. This will enable us to use the constants in classes where the methods are
not required. Example
IMPLEMENTING INTERFACES
Interfaces are used as "superclasses" whose properties are inherited by classes. It
is therefore necessary to create a class that inherits the given interface. This is
done as follows:
class classname implements interfacename
{
body of classname.
}
class Student
{
int rollNumber;
void getNumber(int n)
{
SHWETHA RANI R S 1ST BCA Page 21
OBJECT ORIENTED PROGRAMMING WITH JAVA
rollNumber = n;
}
void putNumber ( )
{
System.out.println (" Roll No : " + rollNumber);
}
}
class Test extends Student
float part1, part2;
void getMarks (float ml, float m2)
part1 = m1;
part2 = m2;
}
void putMarks ( )
{
System.out.println("Marks obtained ");
System.out.println("Part 1 = " + part 1);
System.out.println("Part 2 = " + part 2);
}
}
interface Sports
{
float sportWt = 6.OF;
void putwt ();
}
class Results extends Test implements Sports
{
float total;
public void putWt ( )
{
System.out.println("Sports Wt = " + sportWt);
}
void display ( )
{
total = partl+part2 + sportWt;
put Number();
putMarks();
putWt ();
System.out.println("Total score = " + total);
}
}
class Hybrid
public static void main(String args[])
Results student1 = new Results();
student1.getNumber (1234);
student1.getMarks (27.5F, 33.0F);
student1.display();
JAVA PACKAGES
INTRODUCTION:
Benefits:
• The classes contained in the packages of other programs can be easily reused.
Java
FrequentlyusedAPIpackages
Packagename Contents
java.lang Language support classes. These are classes that Java compiler itself
uses and therefore they are automatically imported.They include
classes for primitive types, strings, math functions, threads
and exceptions.
//save as Simple.java
package mypack;
System.out.println("Welcome to package");
1. import package.*;
2. import package.classname;
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the
current package.
package pack;
public class A{
//save by B.java
package mypack;
import pack.*;
class B{
obj.msg();
2) Using Packagename.classname
If you import package.classname then only declared class of this package will be accessible.
package pack;
public class A{
//save by B.java
package mypack;
import pack.A;
class B{
obj.msg();
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
package pack;
public class A{
//save by B.java
package mypack;
class B{
obj.msg();
Java.util Package
It contains the collections framework, legacy collection classes, event model, date and time facilities,
internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator,
and a bit array).
The package java.util contains a number of useful classes and interfaces. Although the name of
the package might imply that these are utility classes, they are really more important than that. In
fact, Java depends directly on several of the classes in this package, and many programs will find
these classes indispensable. The classes and interfaces in java.util include:
MULTITHREADING IN JAVA
Multithreading is a conceptual programming paradigm where a program
(process) is divided into two or more subprograms (processes), which can be
implemented at the same time in parallel.
LIFECYCLEOFATHREAD
During the lifetime of a thread, there are many states it can enter.They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
1. Newborn State:
2.Runnable State:
This runnable state means that the thread is ready for execution and is
waiting for the availability of the processor. That is,the thread has joined
the queue of threads that are waiting for execution. If all threads have equal
priority, then they are given time slots for execution in round robin
fashion. I.e., first-come, first – serve manner.The thread that relinquishes
control joins the queue at the end and again waits for its turn.This process
3.Running state:
Running means that the processor has given its time to the thread for
its execution. The thread runs until it relinquishes control on its own or it
is pre-empted by a higher priority thread. A running thread may relinquish
its control in one of the following situations.
2. It has been made to sleep, we can put a thread to sleep for a specified
time period using the method sleep (time) where time is in
milliseconds. This means that the thread is out of the queue during this
time period. The thread re-enters the runnable state as soon as this time
period is elapsed.
3. It has been told to wait until some even to occurs.This is done using the wait()
methods.The thread can be scheduled to run again using the notify() method.
4. Blocked State
5. Dead State
Every thread has life cycle. A running thread ends its life when it has completed
executing its run() method.A thread can be killed as soon it is born, or while it is
running or even when it is in “not runnable”(blocked) conditio
Thread methods
Use of yield(),stop(),sleep() methods
class A extends Thread
{
public void run()
{
for (int i =1; i< 5; i++)
{
if(i==1) yield();
System.out.println("\tFrom Thread A : i="+i);
}
System.out.println("exit from A ");
}
}
class B extends Thread
{
public void run ( )
{
for (int j=1; j<=5; j++)
{
System.out.println("\tFrom Thread B: j=”+j);
if (j==3) stop();
System.out.println("Exit from B ");
}
}
class C extends Thread
{
public void run ( )
{
for (int k=1; k<=5; k++)
{
System.out.println("\tFrom Thread C: k = " +k);
if (k==1)
try
{
sleep (1000);
}
catch(Exception e)
{
{
System.out.println("Exit from C ");
}
}
class ThreadMethods
{
public static void main(String args[])
SHWETHA RANI R S 1ST BCA Page 32
OBJECT ORIENTED PROGRAMMING WITH JAVA
{
A threadA= new A( );
B threadB= new B( ); C threadC=new C();
System.out.println("Start thread A");
threadA.start();
System.out.println("Start thread B");
threadB, start();
System.out.println("Start thread C");
threadC.start();
System.out.println("End of main thread");
}
}
IMPLEMENTING THE ‘RUNNABLE’ INTERFACE
Steps:
THREAD SYNCHRONIZATION
So far, we have seen threads that use their own data and methods provided
inside their run () methods. What happens when they try to use data and methods
outside themselves?On such occasions,they may compete for the same resources
and may lead to serious problems. For example, one thread may try to read a record
from a file while another is still writing to the same file. Depending on the
situation, we may get strange results. Java enables overcome this problem using
technique known as synchronization.
..............................
.............................
synchronized(lock–object)
..........................
An interesting situation may occur when two or more threads are waiting
to gain control of a resource. Due to some reason, the condition on which the
waiting threads rely onto gain control does not happen.This results in what is
known as deadlock.
An exception is a condition that is caused by a run – time error in the program. When the
Java interpreter encounters an error such as dividing an integer by zero, it creates an
exception object and throws it.
The error handling code basically consists of two segments, one to detect errors and to
Throw exceptions and the other to catch exceptions and to take appropriate actions.
The basic concepts of exception handling are throwing an exception and catching it.
trybloc
k
Statement that causes
anexception
Exception object creator
catchBlock
Java uses a keyword try to preface a block of code that is likely to cause an
error condition and “throw” an exception. A catch block defined by the keyword
catch “catches” the exception “thrown” by the try block and handles it
appropriately. The catch block is added immediately after the tryblock.
Eg:
....................................
....................................
try
catch(Exceptiontype e )
.....................................
.....................................
The try block can have one or more statements that could generate an
exception. If anyone statement generates an exception, the remaining statements
in the block are skipped and execution jumps to the catch block that is placed next
to the tryblock.
The catch block too can have one or more statements that are necessary to
process the exception. Remember that every try statement should be followed by
at least one catch statement; otherwise compilation error will occur.
{
public static void main(String args[])
int a = 10;
int b = 5;
int c = 5;
int x, y ;
try
{
x = a (b-c); // Exception here
}
catch (ArithmeticException e)
System.out.println("Division by zero");
}
y = a / (b+c);
System.out. println ("y = " + y);
}
}
Output
Division by zero
y =1
MULTIPLECATCHSTATEMENTS
................................
................................
try
catch(Exceptiontype1e)
statement; //processesexceptiontype1
catch(Exceptiontype2e)
statement; //processesexceptiontype2
catch(ExceptiontypeN e)
When an exception in a try block is generated, the Java treats the multiple catch
statements like cases in a switch statement. The first statement whose parameter
matches with the exception object will be executed, and the remaining statements
will skipped.
NotethatJavadoesnotrequireanyprocessingoftheexceptionatall.Wecansimplyh
aveacatch statement with an empty block to avoid program abortion.
Eg:
catch(Exception e);
The catch statement simply ends with a semicolon, which does nothing. This
statement will catch an exception and then ignore it.
Program:Using multiple catch blocks
class Erro4
{
public static void main(String args[])
{
int a[ ] = {5, 10};
int b = 5;
try
{
int x = a[2] / b - a [1];
}
catch (ArithmeticException e)
{
System.out.println (Division by zero");
}
catch (ArraylndexOutOfBounds Exception e)
{
System.out.println("Array index error");
}
catch (ArrayStoreException e)
{
System.out.println ("Wrong data type");
}
int y = a[1] / a[0];
System.out. println ("y = " + y);
}
}
Output:
Array index error
y=2
Java supports another statement known as finally statement that can be used to handle an exception that
is not caught by any of the previous catch statements, finally block can be used to handle any exception
generated within a try block. It may be added immediately after the try block or after the last catch block
When a finally block is defined, this is guaranteed to execute, regardless of whether or not an exception is
thrown. As a result, we can use it to closing files and releasing system resources
try
{
…….
…….
}
finally
{
……
}
Or
try
{
….
…..
SHWETHA RANI R S 1ST BCA Page 40
OBJECT ORIENTED PROGRAMMING WITH JAVA
}
catch(…..)
{
…..
}
catch(…..)
{
…..
}
.
.
.
finally
{
…..
}
class TestFinally
{
public static void main(String args[]
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println(“Finally block is always executed”);
}
System.out.println(“rest of the code”);
}
}
Output:
Finally block is always excecuted
Collections in Java
The Collection in Java is a framework that provides an architecture to store and manipulate the group
of objects.
Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces
(Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet).
Any group of individual objects which are represented as a single unit )illloiooi9l known as the
collection of the objects. In Java, a separate framework named the “Collection Framework” has
been defined in JDK 1.2 which holds all the collection classes and in it.
The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two
main “root” interfaces of Java collection classes.
Before the Collection Framework(or before JDK 1.2) was introduced, the standard methods for
grouping Java objects (or collections) were Arrays or Vectors, or Hashtables. All of these
collections had no common interface. Therefore, though the main aim of all the collections is the
same, the implementation of all these collections was defined independently and had no correlation
among them. And also, it is very difficult for the users to remember all the different methods,
syntax, and constructors present in every collection class.
Java Collections are the one-stop solutions for all the data manipulation jobs such as
storing data, searching, sorting, insertion, deletion, and updating of data. Java collection
responds as a single object, and a Java Collection Framework provides various Interfaces
and Classes.
A Java Collection is a predefined architecture capable of storing a group of elements and behaving
like a single unit such as an object or a group.
Java Collection Framework offers the capability to Java Collection to represent a group of elements
in classes and Interfaces.
Java Collection Framework enables the user to perform various data manipulation operations like
storing data, searching, sorting, insertion, deletion, and updating of data on the group of elements.
Followed by the Java Collections Framework, you must learn and understand the Hierarchy of Java
collections and various descendants or classes and interfaces involved in the Java Collections.
After the Hierarchy of Java collections; you should also get to know the various methods applied to
the Collections in Java to perform the data manipulation operations.
Method Description
Returns true if
isEmpty()
is empty
JavaBeans Introduction…
• JavaBeans are reusable software components for Java
• Build re-useable applications or program building blocks called components that can be
deployed in a network on any major operating system platform.
• They are used to encapsulate many objects into a single object (the bean), so that they can be
passed around as a single bean object instead of as multiple individual objects.
• A JavaBeans is a Java Object that is serializable, has a 0-argument constructor, and allows
access to properties using getter and setter methods.
• Like Java applets, JavaBeans components (or "Beans") can be used to give World Wide Web
pages (or other applications) interactive capabilities such as computing interest rates or varying
page content based on user or browser characteristics.
Advantages
• A Bean obtains all of the benefits of Java's "write once, run anywhere" paradigm.
• The properties, events, and methods of a Bean that are exposed to another application can
be controlled.
• Auxiliary software can be provided to help configure a Bean.
• The configuration settings of a Bean can be saved in a persistent storage and can be
restored at a later time.
• A Bean may register to receive events from other objects and can generate events that are
sent to it.
Disadvantages
• A class with a constructor is subject to being instantiated in an invalid state. If such a class
is instantiated manually by a developer (rather than automatically by some kind of
framework), the developer might not realize that the class has been improperly
instantiated.
• The compiler can’t detect such a problem, and even if it’s documented, there’s no
guarantee that the developer will see the documentation.
• Having to create a getter for every property and a setter for many, most, or all of them, creates
an immense amount of boilerplate code.
JavaBeans API
• The JavaBeans functionality is provided by a set of classes and interfaces in the java.beans
package.
• TCP: TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet Protocol,
which is referred to as TCP/IP.
• UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for
packets of data to be transmitted between applications.