0% found this document useful (0 votes)
22 views

Unit Iv

The document discusses the Java Abstract Window Toolkit (AWT) which provides classes for developing graphical user interfaces in Java. It describes the AWT class hierarchy with Component at the top. Specific AWT classes are then discussed in more detail, including Container, Window, Frame, Panel, Label, Button, TextField, TextArea, Checkbox, CheckboxGroup, Choice, and List. Examples of creating and using instances of each AWT class are provided.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Unit Iv

The document discusses the Java Abstract Window Toolkit (AWT) which provides classes for developing graphical user interfaces in Java. It describes the AWT class hierarchy with Component at the top. Specific AWT classes are then discussed in more detail, including Container, Window, Frame, Panel, Label, Button, TextField, TextArea, Checkbox, CheckboxGroup, Choice, and List. Examples of creating and using instances of each AWT class are provided.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

UNIT-IV

AWT CONTROLS:
Java AWT (Abstract Window Toolkit) is an API to develop Graphical
User Interface (GUI) or windows-based applications in Java.
Java AWT is an API that contains large number of classes and
methods to create and manage graphical user interface ( GUI )
applications. .
Java AWT components are platform-dependent i.e. components are
displayed according to the view of operating system. AWT is heavy
weight i.e. its components are using the resources of underlying
operating system (OS).
The AWT class hierarchy:
The hierarchy of Java AWT classes are given below.

Component class:

Component class is at the top of AWT hierarchy. It is an abstract


class that encapsulates all the attributes of visual component. A
component object is responsible for remembering the current
foreground and background colors and the currently selected text
font.
Container:

Container is a component in AWT that contains another component


like button, text field, tables etc. Container is a subclass of
component class. Container class keeps track of components that
are added to another component.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog

Panel:

Panel class is a concrete subclass of Container. Panel does not


contain title bar, menu bar or border. It is container that is used for
holding components.

Window class:

Window class creates a top level window. Window does not have
borders and menubar.

Frame:

Frame is a subclass of Window and have resizing canvas. It is a


container that contain several different components like button, title
bar, textfield, label etc. In Java, most of the AWT applications are
created using Frame window.
Creating a Frame
There are two ways to create a Frame. They are,
1. By Instantiating Frame class
2. By extending Frame class

1.Creating Frame Window by Instantiating Frame class

import java.awt.*;

public class Testawt


{
Testawt()
{
Frame fm=new Frame(); //Creating a frame
Label lb = new Label("welcome to java graphics"); //Creating a
label
fm.add(lb); //adding label to the frame
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}}

2.Creating Frame window by extending Frame class

package testawt;

import java.awt.*;
import java.awt.event.*;
public class Testawt extends Frame
{
public Testawt()
{
Button btn=new Button("Hello World");
add(btn); //adding a new Button.
setSize(400, 500); //setting size.
setTitle("StudyTonight"); //setting title.
setLayout(new FlowLayout()); //set default layout for frame.
setVisible(true); //set frame visibilty true.
}
public static void main (String[] args)
{
Testawt ta = new Testawt(); //creating a frame.
}}

Points to Remember:

1. While creating a frame (either by instantiating or extending


Frame class), Following two attributes are must for visibility of
the frame:
○ setSize(int width, int height);
○ setVisible(true);
2. When you create other components like Buttons, TextFields,
etc. Then you need to add it to the frame by using the method -
add(Component's Object);
3. You can add the following method also for resizing the frame -
setResizable(true);

user interface components:

AWT Label

In Java, AWT contains a Label Class. It is used for placing text in a


container. Only Single line text is allowed and the text can not be
changed directly.

Label Declaration:

public class Label extends Component implements Accessible

Example:

import java.awt.*;
class LabelDemo1
{
public static void main(String args[])
{
Frame l_Frame= new Frame("studytonight ==> Label
Demo");
Label lab1,lab2;
lab1=new Label("Welcome to studytonight.com");
lab1.setBounds(50,50,200,30);
lab2=new Label("This Tutorial is of Java");
lab2.setBounds(50,100,200,30);
l_Frame.add(lab1);
l_Frame.add(lab2);
l_Frame.setSize(500,500);
l_Frame.setLayout(null);
l_Frame.setVisible(true);
}
}

AWT Button

In Java, AWT contains a Button Class. It is used for creating a


labelled button which can perform an action.

AWT Button Classs Declaration:

public class Button extends Component implements Accessible


import java.awt.*;
public class ButtonDemo1
{
public static void main(String[] args)
{
Frame f1=new Frame("studytonight ==> Button
Demo");
Button b1=new Button("Press Here");
b1.setBounds(80,200,80,50);
f1.add(b1);
f1.setSize(500,500);
f1.setLayout(null);
f1.setVisible(true);
}

Text Components

AWT TextField

In Java, AWT contains aTextField Class. It is used for displaying


single line text.

TextField Declaration:

public class TextField extends TextComponent

Example:

We are creating two textfields to display single line text string. This
text is editable in nature, see the below example.

import java.awt.*;
class TextFieldDemo1{
public static void main(String args[]){
Frame TextF_f= new Frame("studytonight
==>TextField");
TextField text1,text2;
text1=new TextField("Welcome to studytonight");
text1.setBounds(60,100, 230,40);
text2=new TextField("This tutorial is of Java");
text2.setBounds(60,150, 230,40);
TextF_f.add(text1);
TextF_f.add(text2);
TextF_f.setSize(500,500);
TextF_f.setLayout(null);
TextF_f.setVisible(true);
}
}
AWT TextArea

In Java, AWT contains aTextArea Class. It is used for displaying


multiple-line text.

TextArea Declaration:

public class TextArea extends TextComponent

Example:

In this example, we are creating a TextArea that is used to display


multiple-line text string and allows text editing as well.

import java.awt.*;
public class TextAreaDemo1
{
TextAreaDemo1()
{
Frame textArea_f= new Frame();
TextArea area=new TextArea("Welcome to
studytonight.com");
area.setBounds(30,40, 200,200);
textArea_f.add(area);
textArea_f.setSize(300,300);
textArea_f.setLayout(null);
textArea_f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaDemo1();
} }

Check Box:AWT Checkbox


In Java, AWT contains a Checkbox Class. It is used when we want to
select only one option i.e true or false. When the checkbox is
checked then its state is "on" (true) else it is "off"(false).

Checkbox Syntax
public class Checkbox extends Component implements
ItemSelectable, Accessible

Example:

import java.awt.*;
public class CheckboxDemo1
{
CheckboxDemo1(){
Frame checkB_f= new Frame("studytonight
==>Checkbox Example");
Checkbox ckbox1 = new Checkbox("Yes", true);
ckbox1.setBounds(100,100, 60,60);
Checkbox ckbox2 = new Checkbox("No");
ckbox2.setBounds(100,150, 60,60);
checkB_f.add(ckbox1);
checkB_f.add(ckbox2);
checkB_f.setSize(400,400);
checkB_f.setLayout(null);
checkB_f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxDemo1();
} }
Check Box Group

AWT CheckboxGroup

In Java, AWT contains aCheckboxGroup Class. It is used to group a


set of Checkbox. When Checkboxes are grouped then only one box
can be checked at a time.

CheckboxGroup Declaration:

public class CheckboxGroup extends Object implements Serializable

Example:

import java.awt.*;
public class CheckboxGroupDemo
{
CheckboxGroupDemo(){
Frame ck_groupf= new Frame("studytonight
==>CheckboxGroup");
CheckboxGroupobj = new CheckboxGroup();
Checkbox ckBox1 = new Checkbox("Yes", obj, true);
ckBox1.setBounds(100,100, 50,50);
Checkbox ckBox2 = new Checkbox("No", obj, false);
ckBox2.setBounds(100,150, 50,50);
ck_groupf.add(ckBox1);
ck_groupf.add(ckBox2);
ck_groupf.setSize(400,400);
ck_groupf.setLayout(null);
ck_groupf.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupDemo();
} }

Choice

AWT Choice

In Java, AWT contains a Choice Class. It is used for creating a drop-


down menu of choices. When a user selects a particular item from
the drop-down then it is shown on the top of the menu.
Choice Declaration:

public class Choice extends Component implements ItemSelectable,


Accessible

Example:

import java.awt.*;
public class ChoiceDemo
{
ChoiceDemo()
{
Frame choice_f= new Frame();
Choice obj=new Choice();
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
choice_f.add(obj);
choice_f.setSize(400,400);
choice_f.setLayout(null);
choice_f.setVisible(true);
}
public static void main(String args[])
{
new ChoiceDemo();
}}

List Box
In Java, AWT contains a List Class. It is used to represent a list of
items together. One or more than one item can be selected from the
list.

List Declaration:

public class List extends Component implements


ItemSelectable, Accessible

Example:

import java.awt.*;

public class ListDemo

ListDemo()
{

Frame list_f= new Frame();

List obj=new List(6);

obj.setBounds(80,80, 100,100);

obj.add("Red");

obj.add("Blue");

obj.add("Black");

obj.add("Pink");

obj.add("White");

obj.add("Green");

list_f.add(obj);

list_f.setSize(400,400);

list_f.setLayout(null);

list_f.setVisible(true);

public static void main(String args[])


{

new ListDemo();

} }

Panels : The Panel is a simplest container class. It provides space in


which an application can attach any other component. It inherits the
Container class.It doesn't have title bar.
public class Panel extends Container implements Accessible

Example:
import java.awt.*;
public class PanelDemo1{
PanelDemo1()
{
Frame panel_f= new Frame("studytonight ==> Panel Demo");
Panel panel11=new Panel();
panel11.setBounds(40,80,200,200);
panel11.setBackground(Color.red);
Button box1=new Button("On");
box1.setBounds(50,100,80,30);
box1.setBackground(Color.gray);
Button box2=new Button("Off");
box2.setBounds(100,100,80,30);
box2.setBackground(Color.gray);
panel11.add(box1);
panel11.add(box2);
panel_f.add(panel11);
panel_f.setSize(400,400);
panel_f.setLayout(null);
panel_f.setVisible(true);
}
public static void main(String args[])
{
new PanelDemo1();
} }

Scroll Pane: A container class which implements automatic


horizontal and/or vertical scrolling for a single child component.In
the current implementation, a ScrollPane can hold only one
Component and has no layout manager.
A container class which implements automatic horizontal and/or
vertical scrolling for a single child component. The display policy
for the scrollbars can be set to:
1. as needed: scrollbars created and shown only when needed
by scrollpane
2. always: scrollbars created and always shown by the
scrollpane
3. never: scrollbars never created or shown by the scrollpane

public class ScrollPane extends Container

java.lang.Object
|
+----java.awt.Component
|
+----java.awt.Container
|
+----java.awt.ScrollPane
syntax:
scroller = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);
Menu: The object of MenuItem class adds a simple labeled menu
item on menu. The items used in a menu must belong to the
MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is
displayed on the menu bar. It inherits the MenuItem class.
Menu class declaration
public class Menu extends MenuItem implements MenuContainer,
Accessible .

Example:
import java.awt.*;
class MenuDemo1
{
MenuDemo1()
{
Frame menu_f= new Frame("studytonight ==> Menu and
MenuItem Demo");
MenuBarmenu_bar=new MenuBar();
Menu menu11=new Menu("Menu");
Menu sub_menu1=new Menu("Sub Menu =>");
MenuItem a1=new MenuItem("Red");
MenuItem a2=new MenuItem("Light Red");
MenuItem a3=new MenuItem("Drak Red");
MenuItem b1=new MenuItem("Green");
MenuItem b2=new MenuItem("Light Green");
MenuItem b3=new MenuItem("Dark Green");
menu11.add(a1);
sub_menu1.add(a2);
sub_menu1.add(a3);
menu11.add(b1);
sub_menu1.add(b2);
sub_menu1.add(b3);
menu11.add(sub_menu1);
menu_bar.add(menu11);
menu_f.setMenuBar(menu_bar);
menu_f.setSize(400,400);
menu_f.setLayout(null);
menu_f.setVisible(true);
}
public static void main(String args[])
{
new MenuDemo1();
} }

Scroll Bar: The object of Scrollbar class is used to add horizontal


and vertical scrollbar. Scrollbar is a GUI component allows us to see
invisible number of rows and columns.
It can be added to top-level container like Frame or a component
like Panel. The Scrollbar class extends the Component class.
AWT Scrollbar Class Declaration
public class Scrollbar extends Component implements Adjustable,
Accessible
Example:
import java.awt.*;

public class ScrollbarExample1 {

// class constructor

ScrollbarExample1() {

// creating a frame

Frame f = new Frame("Scrollbar Example");


// creating a scroll bar

Scrollbar s = new Scrollbar();

// setting the position of scroll bar

s.setBounds (100, 100, 50, 100);

// adding scroll bar to the frame

f.add(s);

// setting size, layout and visibility of frame

f.setSize(400, 400);

f.setLayout(null);

f.setVisible(true);

public static void main(String args[]) {

new ScrollbarExample1();

} }

Output:
Working with Frame class, Color, Fonts and layout managers:
The class Frame is a top level window with border and title. It uses
BorderLayout as default layout manager.
Class declaration
Following is the declaration for java.awt.Frame class:
public class Frame
extends Window
implements MenuContainer
Java Font
In Java, Font is a class that belongs to the java.awt package. It
implements the Serializable interface. FontUIResource is the direct
known subclass of the Java Font class.
Types of Fonts in Java
There are two types of fonts in Java:
o Physical Fonts
o Logical Fonts

Physical Fonts

Physical fonts are actual Java font library. It contains tables that
maps character sequence to glyph sequences by using the font
technology such as TrueType Fonts (TTF) and PostScript Type 1
Font.
The property of the physical font is that it uses the limited set of
writing systems such as Latin characters or
only Japanese and Basic Latin characters.user can bundle and
instantiate that font by using the createFont() method of the Java
Font class.

Logical Fonts

Java defines five logical font families that are Serif, SansSerif,
Monospaced, Dialog, and DialogInput. It must be supported by the
JRE. Note that JRE maps the logical font names to physical font
because these are not the actual font libraries. For example, AWT
components such as Label and TextField uses logical fonts only.

Font Faces and Names


A font may have many faces such as heavy, regular, medium,
oblique, gothic, etc. All font faces have the similar typograph design.
A Font object have three different names that are:
o Logical font name: It is the name that is used to construct the
font.
o Font face name: It is the name of particular font face. For
example, Helvetica Bold.
o Family name: It is the name of the font family. It determines
the typograph design among several faces.

Java Color Codes


Java programming language allows us to create different types of
applications like windows application or web application. The user
interface is an important factor while developing an application. The
GUI of the Java application can be made interactive using different
colors available in Java programming.
Java Color Constants

The color constants in Java are values that cannot be changed and
can be used with different Java programs.
The following table shows the color constants available in the Java
programming. The all-capital version depicts a constant value.

Java LayoutManagers:The LayoutManagers are used to arrange


components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of
the components in GUI forms. LayoutManager is an interface that is
implemented by all the classes of layout managers.

There are the following classes that represent the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

EVENT HANDLING
Events: An event can be defined as changing the state of an object
or behavior by performing actions.
Actions can be a button click, cursor movement, keypress through
keyboard or page scrolling, etc.
The java.awt.event package can be used to provide various event
classes.

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.

It is a mechanism to control the events and to decide what should


happen after an event occur.
Event sources, Event Listeners:
Event Sources:A source is an object that causes and generates an
event. It generates an event when the internal state of the object is
changed. The sources are allowed to generate several different types
of events.

A source must register a listener to receive notifications for a


specific event. Each event contains its registration method. Below is
an example:

public void addTypeListener (TypeListener e1)

Event Listeners:

An event listener is an object that is invoked when an event triggers.


The listeners require two things; first, it must be registered with a
source; however, it can be registered with several resources to
receive notification about the events. Second, it must implement the
methods to receive and process the received notifications.
The methods that deal with the events are defined in a set of
interfaces. These interfaces can be found in the java.awt.event
package.
For example, the MouseMotionListener interface provides two
methods when the mouse is dragged and moved. Any object can
receive and process these events if it implements the
MouseMotionListener interface.
Event Delegation Model (EDM):
The Delegation Model is available in Java since Java 1.1. it
provides a new delegation-based event model using AWT to
resolve the event problems. It provides a convenient
mechanism to support complex Java programs.

Design Goals

The design goals of the event delegation model are as following:

o It is easy to learn and implement


o It supports a clean separation between application and GUI
code.
o It provides robust event handling program code which is less
error-prone (strong compile-time checking)
o It is Flexible, can enable different types of application models
for event flow and propagation.
o It enables run-time discovery of both the component-
generated events as well as observable events.
o It provides support for the backward binary compatibility with
the previous model.

Syntax:
addTypeListener()
where Type represents the Type of event.

import java.awt.*;
import java.awt.event.*;

public class TestApp {


public void search() {
// For searching
System.out.println("Searching...");
}
public void sort() {
// for sorting
System.out.println("Sorting....");
}

static public void main(String args[]) {


TestApp app = new TestApp();
GUI gui = new GUI(app);
} }

class Command implements ActionListener {


static final int SEARCH = 0;
static final int SORT = 1;
int id;
TestApp app;

public Command(int id, TestApp app) {


this.id = id;
this.app = app;
}
public void actionPerformed(ActionEvent e) {
switch(id) {
case SEARCH:
app.search();
break;
case SORT:
app.sort();
break;
} }}
class GUI {
public GUI(TestApp app) {
Frame f = new Frame();
f.setLayout(new FlowLayout());
Command searchCmd = new Command(Command.SEARCH, app
);
Command sortCmd = new Command(Command.SORT, app);
Button b;
f.add(b = new Button("Search"));
b.addActionListener(searchCmd);
f.add(b = new Button("Sort"));
b.addActionListener(sortCmd);
List l;
f.add(l = new List());
l.add("Alphabetical");
l.add("Chronological");
l.addActionListener(sortCmd);
f.pack();
f.show();
} } Output:

Searching...
Handling Mouse and Keyboard Events:
Events are central to programming for a graphical user
interface. The GUI program must be prepared to respond to
various kinds of events .The most basic kinds of events are
generated by the mouse and keyboard.In Java, events are
represented by objects. Different types of events are
represented by objects belonging to different classes.
For a mouse event, an object belonging to a class called
MouseEvent is constructed.For a keyboard event, an object
belonging to a class called KeyEvent is constructed.After the
event object is constructed, it is passed as a parameter to a
designated subroutine.For a GUI program like Applet,
although there is no main() routine there, there is still a sort
of main routine running somewhere that executes a loop to
response the events. This loop is called an event loop. It’s
part of “the system”.
Example:
import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="MouseEvents" width=300 height=100>

</applet>

*/

public class MouseEvents extends Applet

implements MouseListener, MouseMotionListener {

String msg = "";

int mouseX=0,mouseY=0;
// coordinates of mouse

public void init() {

addMouseListener(this);

addMouseMotionListener(this);
}

// Handle mouse clicked.

public void mouseClicked(MouseEvent me)


{

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse clicked.";

repaint();

// Handle mouse entered.

public void mouseEntered(MouseEvent me)


{

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse entered.";

repaint();
}

// Handle mouse exited.

public void mouseExited(MouseEvent me)


{

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse exited.";

repaint();

// Handle button pressed.

public void mousePressed(MouseEvent me)


{

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "Down";

repaint();
}

// Handle button released.

public void mouseReleased(MouseEvent me)


{

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "Up";

repaint();

// Handle mouse dragged.

public void mouseDragged(MouseEvent me)


{

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " +
mouseY);

repaint();

// Handle mouse moved.

public void mouseMoved(MouseEvent me)


{

// show status

showStatus("Moving mouse at " + me.getX() + ", " +


me.getY());

// Display msg in applet window at current X,Y location.

public void paint(Graphics g)


{

g.drawString(msg, mouseX, mouseY);

}
}

output:
Adapter classes:
Java adapter classes provide the default implementation of
listener interfaces. If we inherit the adapter class, we will not
be forced to provide the implementation of all the methods
of listener interfaces. So it saves code.The adapter classes are
found in java.awt.event, java.awt.dnd and
javax.swing.event packages.

uses of adapter classes:

○ It assists the unrelated classes to work combinedly.

○ It provides ways to use classes in different ways.

○ It increases the transparency of classes.

○ It provides a way to include related patterns in the class.

○ It provides a pluggable kit for developing an application.

○ It increases the reusability of the class.

java.awt.event Adapter classes


Java WindowAdapter Example

// importing the necessary libraries

import java.awt.*;

import java.awt.event.*;

public class AdapterExample {

// object of Frame

Frame f;

// class constructor

AdapterExample() {

// creating a frame with the title

f = new Frame ("Window Adapter");


// adding the WindowListener to the frame

// overriding the windowClosing() method

f.addWindowListener (new WindowAdapter() {

public void windowClosing (WindowEvent e) {

f.dispose();

} });

// setting the size, layout and

f.setSize (400, 400);

f.setLayout (null);

f.setVisible (true);

} // main method

public static void main(String[] args) {

new AdapterExample();

} }

Output:
Java MouseAdapter Example

MouseAdapterExample.java

import java.awt.*;

import java.awt.event.*;

// class which inherits the MouseAdapter class

public class MouseAdapterExample extends MouseAdapter {

// object of Frame class

Frame f;

// class constructor

MouseAdapterExample() {

// creating the frame with the title

f = new Frame ("Mouse Adapter");

// adding MouseListener to the Frame


f.addMouseListener(this);

// setting the size, layout and visibility of the frame

f.setSize (300, 300);

f.setLayout (null);

f.setVisible (true);

// overriding the mouseClicked() method of the MouseAdapter class

public void mouseClicked (MouseEvent e) {

// creating the Graphics object and fetching them from the Frame
object using getGraphics() method

Graphics g = f.getGraphics();

// setting the color of graphics object

g.setColor (Color.BLUE);

// setting the shape of graphics object

g.fillOval (e.getX(), e.getY(), 30, 30);

} // main method
public static void main(String[] args) {

new MouseAdapterExample();

} }

Output:

Inner classes:
Java inner class or nested class is a class that is declared
inside the class or interface.
Additionally, it can access all the members of the outer class,
including private data members and methods.

Syntax of Inner class


class Java_Outer_class{

//code

class Java_Inner_class{

//code

} }
Advantage of Java inner classes

1. Nested classes represent a particular type of relationship that


is it can access all the members (data members and methods)
of the outer class, including private.

2. Nested classes are used to develop more readable and


maintainable code because it logically group classes and
interfaces in one place only.

3. Code Optimization: It requires less code to write.

An inner class is a part of a nested class. Non-static nested classes


are known as inner classes.

Types:

1.Member inner class:A class created within class and outside


method.

2.Anonymous inner class:A class created for implementing an


interface or extending class. The java compiler decides its name.

3.Local inner class:A class was created within the method.

Java Member Inner class

A non-static class that is created inside a class but outside a method


is called member inner class. It is also known as a regular inner
class. It can be declared with access modifiers like public, default,
private, and protected.

Syntax:

class Outer{

//code

class Inner{

//code

} }

Example:

class TestMemberOuter1{

private int data=30;

class Inner{

void msg(){System.out.println("data is "+data);}

public static void main(String args[]){

TestMemberOuter1 obj=new TestMemberOuter1();

TestMemberOuter1.Inner in=obj.new Inner();


in.msg();

} }

Output:

data is 30

Java Anonymous inner class

Java anonymous inner class is an inner class without a name and for
which only a single object is created. An anonymous inner class can
be useful when making an instance of an object with certain "extras"
such as overloading methods of a class or interface, without having
to actually subclass a class.

Java anonymous inner class example using class

TestAnonymousInner.java

abstract class Person{

abstract void eat();

class TestAnonymousInner{

public static void main(String args[]){


Person p=new Person(){

void eat(){System.out.println("nice fruits");}

};

p.eat();

} }

Output:nice fruits

Java Local inner class

A class i.e., created inside a method, is called local inner class in java.
Local Inner Classes are the inner classes that are defined inside a
block. Generally, this block is a method body. Sometimes this block
can be a for loop, or an if clause. Local Inner classes are not a
member of any enclosing classes. They belong to the block they are
defined within, due to which local inner classes cannot have any
access modifiers associated with them. However, they can be
marked as final or abstract. These classes have access to the fields of
the class enclosing it.

Java local inner class example

LocalInner1.java
public class localInner1{

private int data=30;//instance variable

void display(){

class Local{

void msg(){System.out.println(data);}

} Local l=new Local();

l.msg();

public static void main(String args[]){

localInner1 obj=new localInner1();

obj.display();

} }

Output:30

You might also like