0% found this document useful (0 votes)
0 views17 pages

UNIT v Java Notes

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

UNIT v Java Notes

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

UNIT-V

Syllabus: Applet class, Applet structure, Applet life cycle, sample Applet programs. Event
handling: event delegation model, sources of event, Event Listeners, adapter classes, inner
classes.
CONCEPTS OF APPLETS
• Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
• An applet is a small Java application that can be accessed from an internet server,

TS
downloaded automatically, and run along as a part within the webpage.
• Applets provide security. All the applets run in a sandbox like environment. They have
limited access to the client’s system resources. Hence there is no threat of viruses and
other malicious programs.
• Applets allow programmers to develop GUI applications.
• Applets provide GUI through java’s AWT or Swing classes.
Advantages of Applet:
There are many advantages of applet. They are as follows:
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many platforms, including Linux,

CI Windows, Mac Os etc.


DIFFERENCES BETWEEN APPLETS AND CONSOLE APPLICATIONS:
BV

APPLET CLASS
•Every applet application extends the “Applet” class which is available in “java.applet” package.
•“Applet” class contains several methods which allow us to control the applet.
•“java.applet” package also contains three other interfaces namely: AppletContext, AppletStub
and AudioClip.
•Applets provide GUI through AWT(Abstract Window ToolKit) or Swing classes.
•Swing package provides JApplet class. By extending this class we can create applets.

Page No: 1
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
•Swing classes provide extended and easy-to-use functionality over the AWT classes.
•All applets are subclasses of “Applet” class in “java.applet” package or subclasses of “JApplet”
class in “javax.swing” package.
•Applets run within a web browser or by using appletviewer.
•appletviewer is a tool provided by the JDK to run applets.
APPLET LIFE CYCLE
There are five methods in applet life cycle. Those are
1. Applet is initialized.

TS
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

CI Fig: Applet Life cycle


Before learning about how to create applets, let us see the basic methods that help us to
control the execution of an applet.
•Most of the applets override a set of methods which provide the basic functionality for the
applets. Those methods are:
BV
1) init()
2) start()
3) stop()
4) destroy()
5) paint()
•The first four methods are available in the “Applet” class.
•The paint() method is available in the “Component” class.
•When an applet begins, the following methods are executed in sequence:
1) init()
2) start()
3) paint()
•When an applet terminates, the following methods are executed in sequence:
1) stop()
2) destroy()
init() – The init() method is the first method to be executed when an applet is loaded into the
web browser or applet viewer. This method is used to initialize the variables. This method is
called only once during the execution of an applet.
Page No: 2
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
start() – This method is called immediately after the init() method. This method is also called
when the applet stops and restarts its execution.
stop() – This method is called when the web browser leaves the document containing the
applet i.e., when the execution of the applet stops. This method is also executed before the
destroy() method is invoked.
destroy() – This method is called when the JVM decides to remove the applet completely from
the memory. stop() method is always called before destroy() method.
paint() – This method is called after the execution of the start() method. paint() is also called

TS
whenever the output needs to be redrawn, i.e., whenever the window is minimized and
maximized etc… The paint() method contains only one parameter of the type “Graphics”. This
parameter represents the current graphics context. We can use this to draw objects like circle,
square, rectangle etc…
APPLET STRUCTURE
Program Structure for Java Applets:
import java.awt.*;
import java.awt.applet.*;
public class CLASSNAME extends Applet
{
/* ********************* */
/* VARIABLE DECLARATIONS */
CI
{
/* ********************* */
public void init()

/* ***************************** */
/* CREATE AND INITIALIZE OBJECTS */
/* ***************************** */

/* ********************* */
/* ADD OBJECTS TO APPLET */
BV
/* ********************* */
}
}

HTML code for Applet Webpage:


<html>
<head>
<title> TITLE NAME </title>
</head>
<body>
<applet code = "CLASSNAME.class" width = 250 height = 300>
</applet>
</body>
</html>
Example:

Page No: 3
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
Creating and executing applets :

TS
In the previous program, the first import statement is required to import the “Applet” class.
•The second import is required as we are using the “paint()” method which is present in the
“Component” class available in “java.awt” package. Also for using the “Graphics” class.
•Every applet class must extend the predefined class “Applet”.
•The class must be declared as “public” as it will be accessed from outside the program.
•The drawString() method is available in “Graphics” class which is used to print a string to the
GUI. Its syntax is:
void drawString(String message, int x-coordinate, int y-coordinate);

CI
Before executing applets, we must compile the program in the same way as you compile a
console application. Let the name of my file be “MyApplet.java”. So, for compiling we use:
javac MyApplet.java
•Now, execution of applets is different from executing console applications as applets do not
have a main() method. Applets can be executed in two ways:
1) By using any standard web browser( like IE, firefox, chrome)
2) By using “appletviewer” tool provided by Java SDK.
BV

Page No: 4
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
EXECUTING APPLETS (USING APPLET VIEWER):
•By now, you have create two files: MyApplet.java and MyApplet.html.
•applet viewer is a command line tool provided by Java SDK to test the applets before
deploying them to web pages.
•For executing applets using applet viewer, open command prompt, navigate to the location
where your files are present and type the following:
appletviewer MyApplet.html
(or)

TS
If you don't want to create a html page separately, you can embed the <applet> tag within in
the source program file, which is in my example: MyApplet.java
You can now execute your applet program by using the following command at command
prompt:
appletviewer MyApplet.java
Output:

CI
TYPES OF APPLETS:
There are two different applet types. The applet types vary based on how the applet is
embedded into web page. Applet Types are:
• Local Applets – Local applets are applet types that are developed and stored in local
system. The web page will search the local system directories, find the local applet and
BV
execute it. Execution of local applet does not require internet connection.
• Remote Applets – The remote applets are applet types that are developed and stored in
remote computer. The web page requires internet connection to locate and load the
remote applet from the remote computer.
APPLET TAG
<applet> tag
• The <applet> tag in HTML is used to identify the applets in a webpage by the browser
and by applet viewer.
• If there are multiple <applet> tags, applet viewer opens each applet in a separate
window. Whereas browser can load both the applets in a single page.
<applet> tag attributes:
Following are the attributes or options supported by the <applet> tag:
1) codebase: This attribute is used to specify the base URL where the applet file(.class file) is
located. By default this property will be set to the location where the .html file is available.
2) code: This attribute is used to specify the name of the applet file(.class file)
3) width: Used to specify the width(in pixels) of the applet’s display area.
4) height: Used to specify the height(in pixels) of the applet’s display area.
Page No: 5
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
5) name: This attribute is used to specify the name of the applet. It is used to identify one
applet from another, if there are multiple applets in the same webpage.
6) alt: This attribute is used display a short message when the browser identifies the <applet>
tag, but is not able to load the applet into browser.
7) align: This attribute is used to specify the alignment of the applet in the browser.
8) vspace: Used to specify some gap above and below the applet’s display area.
9) hspace: Used to specify some gap left and right to the applet’s display area.
10) param: Used to specify the parameters for the applet. This param tag has attributes,

TS
“name” and “value”. We use “name” attribute to specify the name of the parameter and
“value” attribute to specify the value of the parameter.
paint(), update() and repaint()
The class Component defines methods called paint(), update() and repaint().
paint():
1. paint() method is called each time your applet’s must be redrawn. It can occur for several
reasons:-
a) The window in which the applet is running may be overwritten by another window and
then uncovered.
b) The applet window may be minimized then restored.
c) When applet begins execution.
2. The paint() method has one parameter of type Graphics.

CI
3. This contains the graphics context, which describes the graphic environment.
update():
1. Sometimes your applet may need to override another method defined by the AWT-
update().
2. This method is called when your applet has requested that, a portion of window needs
to be redrawn.
3. Default version of update() first fills an applet with the default background color and
then calls paint.
4. If you fill the background using a different color in paint, user will experience a flash of
BV
the default background each time window is repainted (whenever update() is called).
5. One way to avoid this problem is to override update so that it performs all necessary
activities. Then have paint() simply call update().
repaint():
1. We can call repaint() method when you want the applet area to be re drawn.
2. The repaint() method calls the update().
3. The default action of update() method is to clear the applet area and call the paint().

APPLETS AND GRAPHICS: One of the most important features of Java is its ability to draw
graphics. We can write Java applets that can draw lines, figures of different shapes, images, and
text in different fonts, styles, and colors. Every applet has its own area on the screen known as
canvas, where it creates display. Java coordinate system has the origin (0,0) in the upper-left
corner. Positive x values are to the right and +ve y values to the bottom. The values of (x,y) are
in pixels.
Graphics Class Methods:
drawArc (x, y, width, height, startAngle, arcAngle)
drawLine() – draws a straight line
Page No: 6
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
drawLine(x,y,width, height)
drawOval(x,y,width,height)_ If width and height are same, it draws a circle
drawPolygon() - draws a hollow polygon
drawRect(x,y,width,height)
drawRoundRect() - draws a hollow round cornered rectangle
drawString() – display a text string
fillArc() - draw a filled arc
fillOval(x,y,width,height)

TS
fillPolygon()
fillRect(x,y,width,height)
fillRoundRect()
getColor ()– retrieve the current drawing colour
getFont()
setColor() – sets the drawing color
setFont()
SAMPLE APPLET PROGRAMS
APPLET TO MAKE A SMILEY FACE:
In this applet, we’ll be making a face using different shapes. The applet package contains
methods to draw an Oval, a line, rectangle, rounded rectangle, arc, etc. To make a smiley face,
we will be using Ovals and arcs.
CI
Syntax for drawing an Oval:
obj.drawOval(x,y,width,height);
In the above syntax, drawOval() method needs to be supplied four arguments. The first two
arguments to set the position of the oval along the x axis and the y axis and the last two
arguments to set the width and height of the oval.
Syntax for drawing an Arc:
obj.drawArc(x,y,width,height,starting angle,arc angle);
The drawArc() method needs to be accessed using an object with the dot operator. It needs
BV
to be supplied six arguments. The first two arguments to set the position of the arc along
the x axis and the y axis and the next two to set the width and height of the arc respectively.
The last two arguments determine the starting angle of the arc and angle of the arc.
Difference between drawOval() and fillOval():
‘draw’ is used to draw the outline of the given shape whereas ‘fill’ will fill the shape with the color
which is set in the color pallet. To understand the difference, please refer the below program
Smiley face.java
/* <applet code = "Smileyface" width = 300 height = 300> </applet> */
import java.applet.*;
import java.awt.*;
public class Smileyface extends Applet
{
public void paint (Graphics g) {
setBackground(Color.green);
g.setColor(Color.yellow);
g.fillOval(65, 65, 125, 125);//Draws Face
g.setColor(Color.black);
Page No: 7
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
g.fillOval(95, 101, 20, 20);//Left eye
g.fillOval(135, 101, 20, 20);//Right eye
g.drawArc(100, 140, 50,25, 180, 180);//Mouth
g.drawString("Keep Smiling!!!", 180, 170);
}}
Output: G:\>javac Smileyface.java
G:\>appletviewer Smileyface.java

TS
Write an applet program for printing human face.
import java.awt.* ;
import java.applet.* ;

CI
/* <applet code = "face" width = 300 height = 300> </applet> */
public class face extends Applet
{
public void paint(Graphics g){
g.setColor(Color.yellow);
g.fillOval(40,40,120,150); //Head
g.setColor(Color.black);
g.drawOval(57,75,30,20); //Left Pupil
g.drawOval(110,75,30,20); //Right Pupil
BV
g.fillOval(68,81,10,10); //Left eye
g.fillOval(121,81,10,10); //Right eye
g.drawOval(85,100,30,30); //Nose
g.fillArc(60,125,80,40,180,180); //Mouth
g.drawOval(25,92,15,30); //Left ear
g.drawOval(160,92,15,30); //Right ear
}}
Output:

Page No: 8
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
EVENT HANDLING
Introduction:
What is an Event?
Change in the state of an object is known as event i.e. event describes the change in state of
source. Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page are the activities that causes an

TS
event to happen.
Types of Events:
The events can be broadly classified into two categories:
• Foreground Events - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering
a character through keyboard, selecting an item from list, scrolling the page etc.
• Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer
expires, an operation completion are the example of background events.
What is Event Handling?
Event Handling is the mechanism that controls the event and decides what should happen if an

CI
event occurs. This mechanism has the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events. Let's have a brief
introduction to this model.
EVENT DELEGATION MODEL
The way, in which events are handled in java, using listener objects is called Event Delegation
model. We can make objects of any class listener objects by making the class implement a
listener interface.
•Java follows delegation event model for handling events in programs.
BV
•In this model, a source generates events which are detected by the listeners registered with it.
•The listener processes the event and returns control to the program.
•The advantage of the delegation event model is, it separates the event handling logic from the
rest of the programming logic.
•In delegation event model, a listener must be registered with the source to receive event
notifications.
•Java 1.0 does not use the delegation event model. In Java 1.0, when an event is generated, it
was notified to all the components even though it is not required. This is a disadvantage in Java
1.0’s event handling mechanism.
•Using delegation model is easy. It is a two step process:
1) To detect certain events, implement the required interfaces.
2) We must register/unregister the listeners with the source to receive the event notifications.
The event model is based on the Event Source and Event Listeners. Event Listener is an object
that receives the messages / events. The Event Source is any object which creates the message
/ event. The Event Delegation model is based on – The Event Classes, The Event Listeners, Event
Objects.
There are three participants in event delegation model in Java:
Page No: 9
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
- Event Source – the class which broadcasts the events
- Event Listeners – the classes which receive notifications of events
- Event Object – the class object which describes the event.
An event occurs (like mouse click, key press, etc) which is followed by the event is broadcasted
by the event source by invoking an agreed method on all event listeners. The event object is
passed as argument to the agreed-upon method. Later the event listeners respond as they fit,
like submit a form, displaying a message / alert etc.

TS
CI
What happens internally at a button click?

We know the events are handled by listeners and ActionListener handles the events of a
button. Observe the following skeleton code.
BV

The above program contains a small part of event handling Java code, and is used here just for
the explanation of internal event handling Java mechanism.

Page No: 10
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
A button object btn is created for which events are yet to be linked. For this, the first step is
implementing ActionListener to the class ButtonDemo. In the second step, we link or register
the button btn with the ActionListener. For this addActionListener() method of Button class is
used. The parameter "this" refers the ActionListener.
btn.addActionListener(this);
With the above statement, btn is linked with the ActionListener.
1. When the button btn is clicked, the button generates an event called ActionEvent. It is the
nature of the button taken care by JVM.

TS
2. This ActionEvent reaches the ActionListener because we registered the button with
ActionListener earlier.
3. Now, the question is, what ActionListener does with the ActionEvent object it received?
The ActionListener simply calls actionPerformed() method and passes the ActionEvent object to
the parameter as follows.
public void actionPerformed(ActionEvent e)
The parameter for the above method comes from ActionListener.
4. Finally the ActionEvent object generated by the button btn reaches the e object of
ActionEvent. All this is done by JVM implicitly. For this reason, the getActionCommand()
method of ActionEvent class knows the label of the button btn.
String str = e.getActionCommand();
The e represents an object of ActionEvent and the value for the e is coming from button btn. str

CI
is nothing but the label of the button OK.
Next question is how the parameter "this" refers the ActionListener only? Why not your own
program object ButtonDemo, or a Frame or ActionEvent?
You are right cent percent to think so. Then how to answer the above question. For the answer,
we must refer the method signature of addActionListener() method as defined in Button class.
Following is the one.
public synchronized void addActionListener(ActionListener);
Observe, the parameter must be an object of ActionListener. When we pass "this" to
addActionListener() method, the JVM tries to convert "this" into an object of ActionListener
BV
because the method demands it. The JVM finds it, in the class declaration, after implements
keyword and simply links btn to ActionListener. To have a proof, just remove "implements
ActionListener" and compile the program, the program does not compile.
This type of event handling mechanism designed by the designers follows "Observer design
pattern". The ActionListener observes always the button when it gets clicked. This type of
event handling model is known as "delegation event model". In this model, responsibility of
event handling is delegated (assigned) to listeners.
java.awt.event Description
A source generates an Event and send it to one or more listeners registered with the
source. Once event is received by the listener, they processes the event and then return. Events
are supported by a number of Java packages, like java.util, java.awt and java.awt.event.
Important Event Classes and Interfaces:
Event Classes Description Listener Interface
generated when button is pressed, menu-item is
ActionEvent ActionListener
selected, list-item is double clicked

Page No: 11
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
generated when mouse is dragged,
MouseEvent moved,clicked,pressed or released also when the MouseListener
enters or exit a component

KeyEvent generated when input is received from keyboard KeyListener

ItemEvent generated when check-box or list item is clicked ItemListener

TS
generated when value of textarea or textfield is
TextEvent TextListener
changed

MouseWheelEvent generated when mouse wheel is moved MouseWheelListener

generated when window is activated,


WindowEvent deactivated, deiconified, iconified, opened or WindowListener
closed

generated when component is hidden, moved,


ComponentEvent ComponentEventListener
resized or set visible

CI
ContainerEvent
generated when component is added or
removed from container

AdjustmentEvent generated when scroll bar is manipulated

FocusEvent
generated when component gains or losses
keyboard focus
ContainerListener

AdjustmentListener

FocusListener

SOURCES OF EVENTS
An event source is the object that generates an event.
BV
For e.g. if you click a button, it is a source of event.
A source must register listeners in order for the listeners to receive notifications about a
specific type of event.
Each type of event has its own registration method.
Syntax: public void addTypeListener (TypeListener el)
Here, type is the name of an event and el is reference to the event listeners. For e.g.: the
method that registers a mouse motion is called addMouseMotionListener()
• When an event occurs, all registered listeners are notificated and receive a copy of
event object and this is called ‘multicasting’ the event.
• Some sources may allow only one listener to register. It is called ‘unicasting’ the event.
Syntax:
public void addTypeListener(TypeListener el) throws java.util.TooManyListenersException
A source also allows a listener to unregister an interest in a specific type of event.
Syntax:
public void removeTypeListener(TypeListener el)

Page No: 12
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
EVENT LISTENERS
A listener is an object that is notified when an event occurs. It has 2 requirements:-
1. It must have been registered with one or more sources to receive notifications about
specific type of events.
2. It must implement methods to receive and process these notifications.
Event listener is a method that understands an event and processes it.
Java AWT Listeners are a group of interfaces from java.awt.event package. Listeners are
capable to handle the events generated by the components like button, choice, frame etc.

TS
These listeners are implemented to the class which requires handling of events.
public class ButtonDemo1 extends Frame implements ActionListener
The class ButtonDemo1 implements ActionListener as ButtonDemo1 includes some buttons
which require event handling. The button events (known as action events) are handled by
ActionListener.
Even though, some listeners handle the events of a few components, generally every
component event is handled by a separate listener. For example, the ActionListener handles
the events of Button, TextField, List and Menu. But these types are very rare.
Example of Event Handling:
KEY EVENTS:
Key events indicate when the user is typing at the keyboard. Specifically, key events are
fired by the component with the keyboard focus when the user presses or releases keyboard
CI
keys.To read from the keyboard it is necessary to register an object which be in-charge of
"listening if a key is pressed". This object is known as "Listener" and it will have methods that
will be called when someone presses a key.
To handle keyboard events, we must implement the “KeyListener” interface.
•When the “KeyListener” interface is implemented, we must provide implementations for three
methods available in that interface. They are:
1) keyPressed()
2) keyReleased()
3) keyTyped()
BV
•To get the character, when the keyTyped() event occurs, we use the method:
char getKeyChar()
Ex:
/*Keyboard events in JAVA*/
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
/*<applet code="Test" width=400 height=300 >
</applet>*/
public class Test extends Applet implements KeyListener
{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
Page No: 13
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)

TS
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}

CI•
ADAPTER CLASSES
Java provides a special feature, called an adapter class that can simplify the creation of
event handlers in certain situations.
• An adapter class provides an empty implementation of all methods in an event listener
BV
interface i.e this class itself write definition for methods which are present in particular
event listener interface. However this definition does not affect program flow or
meaning at all.
• Adapter classes are useful when you want to receive and process only some of the
events that are handled by a particular event listener interface.
• You can define a new class to act as an event listener by extending one of the adapter
classes and implementing only those events in which you are interested.
• E.g. Suppose you want to use mouseClicked Event or method from MouseListener, if
you do not use adapter class then unnecessarily you have to define all other methods
from MouseListener such as mouseReleased, mousePressed etc.
• But If you use adapter class then you can only define mouseClicked method and don’t
worry about other method definition because class provides an empty implementation
of all methods in an event listener interface.
• Below Table Indicates Listener Interface with their respective adapter class.

Page No: 14
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
Listener Interface Adapter Class
ComponentListener ComponentAdapter
ContainerListener ContainerAdapter
FocousListener FocousAdapter
KeyListener KeyAdapter
MouseListener MouseAdapter

TS
MouseMotionListener MouseMotionAdapter
WindowListener WindowAdapter
Ex:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="MainClass" height="400" width = "500">
</applet>*/
public class MainClass extends Applet
{
public void init()
{

}
}
CI
addMouseListener(new AdapterTest(this));

// End of MainClass
// AdapterTest Created
class AdapterTest extends MouseAdapter
{
MainClass MainClassObj;
public AdapterTest(MainClass MainClassObj)
{
BV
this.MainClassObj=MainClassObj;
}
public void mouseClicked(MouseEvent me)
{
MainClassObj.showStatus("Mouse Has Been Clicked ");
}
} // End of AdapterTest Class
Output:

Page No: 15
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
INNER CLASSES
A non-static class that is created inside a class but outside a method is called member inner
class.
Syntax:
class Outer{
//code
class Inner{
//code

TS
}
}
Java Member inner class example:
In this example, we are creating msg() method in member inner class that is accessing the
private data member of outer class.
class TestMemberOuter1
{
private int data=30;
class Inner
{
void msg()
{
CI}
}
System.out.println("data is "+data);

public static void main(String args[])


{
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
BV
}
Output: data is 30
Java Anonymous inner class:
A class that has no name is known as anonymous inner class in java. It should be used if you
have to override method of class or interface. Java Anonymous inner class can be created by
two ways:
1. Class (may be abstract or concrete).
2. Interface
Java anonymous inner class example using class
abstract class Person
{
abstract void eat();
}
class TestAnonymousInner
{
public static void main(String args[])
{
Page No: 16
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS
Person p=new Person()
{
void eat()
{
System.out.println("nice fruits");
}
};
p.eat();

TS
}
}
Output: nice fruits
Java anonymous inner class example using interface:
interface Eatable
{
void eat();
}
class TestAnnonymousInner1
{
public static void main(String args[])
{

CI
{
Eatable e=new Eatable()

};
public void eat()
{

}
System.out.println("nice fruits");

e.eat();
}
BV
}
Output:
nice fruits

******************************************************************************

Page No: 17
Prepared By,
A.P.V.D.L.KUMAR,
Training and Placement Officer,BVCITS

You might also like