0% found this document useful (0 votes)
4 views26 pages

Java Notes UNIT 4

Java Swing is a GUI toolkit that enhances the functionality of AWT, providing a rich set of components for building platform-independent desktop applications. It employs MVC architecture for better organization and maintainability, allowing for customizable appearances and efficient event handling. Swing components include various containers and controls, which can be arranged using layout managers to create interactive user interfaces.
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)
4 views26 pages

Java Notes UNIT 4

Java Swing is a GUI toolkit that enhances the functionality of AWT, providing a rich set of components for building platform-independent desktop applications. It employs MVC architecture for better organization and maintainability, allowing for customizable appearances and efficient event handling. Swing components include various containers and controls, which can be arranged using layout managers to create interactive user interfaces.
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

java

Unit-5 Chapter-1
Introduction to Java Swing
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit [AWT]. Java Swing
offers much-improved functionality over AWT, new components, expanded components features, and excellent event
handling with drag-and-drop support.
Swing is a graphical user interface (GUI) toolkit within Java, forming a key part of the Java Foundation Classes (JFC). It
provides a comprehensive set of components for building desktop applications with rich and interactive user interfaces.

Key aspects of Swing:

 Platform Independence:

Unlike its predecessor, AWT (Abstract Window Toolkit), Swing components are entirely written in Java,
making them "lightweight" and ensuring a consistent look and feel across different operating systems
(Windows, macOS, Linux).

 Rich Component Set:


Swing offers a wide array of GUI components, from basic elements like buttons (JButton), labels (JLabel),
and text fields (JTextField) to more advanced controls such as tables (JTable), trees (JTree), and tabbed
panes (JTabbedPane).

 Pluggable Look and Feel:

Swing allows developers to customize the visual appearance of their applications, offering various "look and
feel" options that can emulate native platform styles or provide unique custom designs.

 MVC Architecture:

Swing components often employ a Model-View-Controller (MVC) architecture, separating the data (model),
its visual representation (view), and the user interaction logic (controller), promoting modularity and
maintainability.

 Event Handling:

Swing uses a delegation event model for handling user interactions. This involves event sources
(components generating events), event objects (containing information about the event), and event listeners
(objects that respond to specific events).

 Containers and Components:

Swing GUIs are built using a hierarchy of containers and components. Containers (e.g., JFrame, JPanel)
hold and organize other components, while components are the individual visual controls that users interact
with.

 Layout Managers:
Swing provides various layout managers (e.g., FlowLayout, BorderLayout, GridLayout) to control the
positioning and sizing of components within containers, ensuring responsive and well-organized interfaces.
In essence, Swing empowers Java developers to create sophisticated and platform-independent desktop
applications with a high degree of control over the user experience.
Program:1
import [Link];
public class SimpleFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame("My First JFrame");
[Link](400, 300);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
OutPut:

MVC architecture

MVC (Model-View-Controller) is an architectural pattern widely used in Java for building applications,
particularly web applications. It separates an application into three interconnected components, each with a
distinct responsibility:

 Model:
 Represents the application's data and business logic.

 Handles data storage, retrieval, and manipulation (e.g., interacting with a database).

 It is independent of the user interface.


 View:
 Represents the user interface (UI) and displays data to the user.

 Presents information retrieved from the Model.

 Captures user interactions (e.g., button clicks, form submissions).

 Examples in Java web applications include JSP files or templating engines like Thymeleaf.
Controller:
 Acts as an intermediary between the Model and View.

 Receives and processes user input from the View.

 Interprets the input and calls the appropriate methods in the Model to update data or perform operations.

 Selects the appropriate View to display the results.

 In Java web applications, controllers are typically implemented using Servlets or frameworks like Spring
MVC.
How MVC Works in Java (General Flow):

 A user interacts with the View (e.g., clicks a button on a web page).

 The Controller receives this user input.

 The Controller processes the input and, if necessary, interacts with the Model to retrieve or update data.

 The Model performs the requested operations and returns the results to the Controller.

 The Controller then selects the appropriate View to display the updated information or results.

 The View renders the data and presents it to the user.

Benefits of MVC in Java:

 Separation of Concerns:

Clearly separates presentation, business logic, and data, making the application more organized and easier to
understand.

 Maintainability:
Changes in one component (e.g., UI changes in the View) are less likely to impact other components,
simplifying maintenance.

 Testability:

Each component can be tested independently, improving the overall testability of the application.

 Reusability:

Model and Controller components can potentially be reused in different Views or applications.

 Parallel Development:
Different teams or developers can work on the Model, View, and Controller components simultaneously.

Java Swing Components


Java Swing components are a set of graphical user interface (GUI) elements used to build interactive
applications in Java. They are part of the Java Foundation Classes (JFC) and are known for being
"lightweight" and platform-independent, meaning they are written entirely in Java and do not rely on the
underlying operating system's native GUI toolkit.
Swing components can be broadly categorized into two types:
1. Top-Level Containers: These are the main windows or frames that hold other components.

 JFrame:
A top-level window with a title bar, borders, and options for minimizing, maximizing, and closing.
 JDialog:
A pop-up window typically used for displaying messages or getting specific input from the user.
 JApplet:
A top-level container for applets embedded in web pages (though applets are largely deprecated now).

2. Intermediate Containers and Components: These are elements placed within top-level containers to
organize the layout and provide user interaction.

 JComponent: The base class for most Swing components, providing common functionalities like pluggable
look and feel, accessibility support, and event handling.
 JPanel: A general-purpose lightweight container used to group and organize other components within a
frame or dialog.
 JButton: A push-button component that triggers an action when clicked.
 JLabel: A component used to display uneditable text or images.
 JTextField: A single-line text input field.
 JPasswordField: A specialized text field for password entry, obscuring the input characters.
 JTextArea: A multi-line text area for displaying or editing larger blocks of text.
 JCheckBox: A component that allows the user to select or deselect an option.
 JRadioButton: A component used in groups where only one option can be selected at a time.
 JComboBox: A drop-down list that allows the user to select one item from a list.
 JList: A component that displays a list of items from which the user can select one or more.
 JTable: A component for displaying data in a tabular format.
 JTree: A component for displaying hierarchical data in a tree-like structure.
 JSlider: A component that allows the user to select a value by sliding a knob within a bounded interval.
 JSpinner: A single-line input field that lets the user select a number or object value from an ordered
sequence using up/down arrows or direct input.
 JMenuBar, JMenu, JMenuItem: Components used to create menu bars, menus within the menu bar, and
individual menu items within a menu.
 JFileChooser: A dialog window that allows the user to select files or directories.
 JOptionPane: Provides standard dialog boxes for displaying messages or prompting for input.
 JProgressBar: Displays the progress of a task towards completion.
These components can be combined and arranged using various layout managers
(e.g., BorderLayout, FlowLayout, GridLayout, GridBagLayout) to create complex and visually appealing
user interfaces.

Program:
import [Link].*;
import [Link].*;
public class ChatFrameExample
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Chat Frame");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](400, 400);
JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("FILE");
JMenu m2 = new JMenu("Help");
[Link](m1);
[Link](m2);
JMenuItem m11 = new JMenuItem("Open");
JMenuItem m22 = new JMenuItem("Save as");
[Link](m11);
[Link](m22);

JPanel panel = new JPanel();


JLabel label = new JLabel("Enter Text");
JTextField tf = new JTextField(10);
JButton send = new JButton("Send");
JButton reset = new JButton("Reset");
[Link](label);
[Link](tf);
[Link](send);
[Link](reset);

JTextArea ta = new JTextArea();

[Link]().add([Link], panel);
[Link]().add([Link], mb);
[Link]().add([Link], ta);

[Link](true);
}
}

OutPut:

Java Swing containers


Java Swing containers are specialized components designed to hold and organize other Swing
components, such as buttons, labels, and text fields, within a graphical user interface (GUI). They provide
the structure and layout management for building Swing applications.

There are generally two main types of Swing containers:


 Top-Level Containers:

These are the root windows of a Swing application and are typically heavyweight components, meaning they
rely on the underlying operating system's windowing system.

 JFrame: The most common top-level container, representing a standard window with a title bar, minimize,
maximize, and close buttons.

 JDialog: A top-level container used for creating dialog boxes, which are typically smaller, temporary
windows used for specific user interactions (e.g., confirmation, input).

 JWindow: A simpler top-level container without a title bar or borders, often used for splash screens or
custom window designs.

 JApplet: Used for creating applets that run within a web browser, although its use has significantly declined.
 General-Purpose Containers:
These are lightweight components that can be placed within top-level containers or other general-purpose
containers to organize and manage the layout of components.
 JPanel: A versatile and commonly used container for grouping components, applying different layout
managers, and creating sub-sections within a larger GUI.

 JScrollPane: A container that provides scroll functionality to its contained component, useful when the
content exceeds the visible area.

 JLayeredPane: Allows components to be placed on different "layers" within the same container, enabling
overlapping and z-order control.

 JSplitPane: Divides a container into two resizable sections, allowing the user to adjust the division between
them.

 JTabbedPane: Provides a way to organize multiple panels into a tabbed interface, where only one tab's
content is visible at a time.
Key characteristics of Swing containers:

 Containment hierarchy:

Containers can hold other containers, creating a hierarchical structure for the GUI.

 Layout Managers:

Containers use layout managers (e.g., BorderLayout, FlowLayout, GridLayout, GridBagLayout) to control
the positioning and sizing of their contained components.

 Adding and Removing Components:

Containers provide methods like add() and remove() to manage their child components.

 Painting and Drawing:


Containers are responsible for painting themselves and their contained components.
Java Swing, Layout Managers
In Java Swing, Layout Managers are crucial for arranging and sizing components within a container (like
a JFrame or JPanel). They provide a flexible and platform-independent way to design user interfaces that
adapt to different screen sizes and resolutions. Instead of manually specifying the exact pixel coordinates for
each component, you delegate the positioning and sizing tasks to a layout manager.

Here's a breakdown of commonly used Swing Layout Managers:

1. BorderLayout
2. BoxLayout
3. CardLayout
4. FlowLayout
5. GridBagLayout
6. GridLayout
7. GroupLayout
8. SpringLayout

BorderLayout:-

Every content pane is initialized to use a BorderLayout. (As Using Top-Level Containers explains, the content
pane is the main container in all frames, applets, and dialogs.) A BorderLayout places components in up to
five areas: top, bottom, left, right, and center. All extra space is placed in the center area. Tool bars that are
created using JToolBar must be created within a BorderLayout container, if you want to be able to drag and
drop the bars away from their starting positions.

BoxLayout
The BoxLayout class puts components in a single row or column. It respects the components' requested maximum sizes
and also lets you align components.

CardLayout

The CardLayout class lets you implement an area that contains different components at different times.
A CardLayout is often controlled by a combo box, with the state of the combo box determining which panel
(group of components) the CardLayout displays. An alternative to using CardLayout is using a tabbed pane,
which provides similar functionality but with a pre-defined GUI.

FlowLayout

FlowLayout is the default layout manager for every JPanel. It simply lays out components in a single row,
starting a new row if its container is not sufficiently wide. Both panels in CardLayoutDemo,
shown previously, use FlowLayout..

GridBagLayout

GridBagLayout is a sophisticated, flexible layout manager. It aligns components by placing them within a grid
of cells, allowing components to span more than one cell. The rows in the grid can have different heights, and
grid columns can have different widths.

GridLayout
GridLayout simply makes a bunch of components equal in size and displays them in the requested number of
rows and columns.

GroupLayout

GroupLayout is a layout manager that was developed for use by GUI builder tools, but it can also be used
manually. GroupLayout works with the horizontal and vertical layouts separately. The layout is defined for
each dimension independently. Consequently, however, each component needs to be defined twice in the
layout. The Find window shown above is an example of a GroupLayout.

SpringLayout

SpringLayout is a flexible layout manager designed for use by GUI builders. It lets you specify precise
relationships between the edges of components under its control. For example, you might define that the left
edge of one component is a certain distance (which can be dynamically calculated) from the right edge of a
second component. SpringLayout lays out the children of its associated container according to a set of
constraints,
Unit-5 Chapter-2

Event Handling in java


An event is a change in the state of an object triggered by some action such as Clicking a button, Moving
the cursor, Pressing a key on the keyboard, Scrolling a page, etc. In Java, the [Link] package
provides various event classes to handle these actions.

The delegation event model is a pattern for handling events, particularly in GUIs, where an event source
(like a button) generates an event and "delegates" the processing to one or more registered
listeners. Listeners must register with the source to receive notifications, ensuring that only interested
objects handle events, which improves efficiency by separating event generation from event handling
logic. This model is fundamental to many GUI toolkits like AWT and Swing.
Key components
 Event:
An object that describes a state change in the source, such as a button click or a mouse movement.
 Event Source:
The object that generates the event when its internal state changes, such as a GUI component.
 Event Listener:
An object that receives and processes events. Listeners must be registered with the source to receive
notifications.
How it works
1. A user action occurs on the event source (e.g., a user clicks a button).
2. The event source creates an event object to describe the action.
3. The source notifies all registered listeners by calling a specific method on the listener object, passing the
event object as an argument.
4. The listener then processes the event and performs the required action.
Benefits
 Separation of concerns: It cleanly separates the code that generates the event (the user interface logic) from
the code that handles it (the application logic).
 Efficiency: Notifications are sent only to listeners that have registered interest, eliminating the overhead of
older models where events were propagated up the hierarchy even if not handled.
 Modularity: The design promotes more modular and organized code.
Event Source :-
An event source is a component or system that generates events, which can range from log data in a security
context to specific user actions in an application. In IT, event sources can be applications, servers, or
services that log activities like user logins or network connections. In web development, it can be an object
like a button that triggers an event when clicked, or a service like FullCalendar that uses a JSON feed as an
event source.

In IT and Security
 Definition:

An IT asset that produces log events, which are then collected, analyzed, and used for monitoring and
security purposes.

 Examples:
 LDAP, Active Directory, and VPNs (provide user-related data)

 Firewalls and DNS servers

 Applications, servers, or other IT assets


In Software Development
 Definition:

A component that provides data for events, such as a data feed for a calendar, a user interface element, or a
function that generates events.

 Examples:
 A simple array of event objects

 A URL to a JSON feed

 A button element that generates a click event

 A function that dynamically creates events


In Web Development
 Definition:

A JavaScript object used for server-sent events, establishing a persistent connection to a server to receive
updates in real-time.

 Examples:
 Receiving live social media status updates

 Getting news feeds

 Delivering data into client-side storage


In Event Sourcing architectural pattern
 Definition:

An event is an immutable fact that represents a change in the domain, and the sequence of all these events is
the "source of truth" for the system's state.
 Examples:
 Instead of storing a bank account's current balance, you store events like fundsDeposited and fundsWithdrawn.

 The current balance is then calculated by replaying these events.

Event Listeners:-

In Java, event listeners are a core component of event handling, particularly in GUI programming with AWT
and Swing. They implement the Observer design pattern, allowing objects to "listen" for and respond to
specific events triggered by other objects (event sources).
Here's a breakdown of how event listeners work in Java:

1. Event Source:

 An event source is an object that generates events. In GUI applications, this is typically a component like
a JButton, JTextField, or JFrame.
2. Event Object:

 When an event occurs (e.g., a button click, a key press), an event object is created. This object encapsulates
information about the event, such as its source and specific details (e.g., mouse coordinates for
a MouseEvent). Event objects typically extend [Link].
3. Event Listener Interface:

 An event listener is an object that implements a specific event listener interface from
the [Link] package (or [Link] for Swing-specific listeners). Examples include:
o ActionListener: For ActionEvent (e.g., button clicks).

o MouseListener: For MouseEvent (e.g., mouse clicks, presses, releases).

o KeyListener: For KeyEvent (e.g., key presses, releases).

o WindowListener: For WindowEvent (e.g., window closing, opening).


4. Listener Implementation:

 A class implements the chosen listener interface and provides concrete implementations for its
methods. These methods are the "event handlers" that define the actions to be taken when the corresponding
event occurs.
5. Registration:

 The implemented listener object is registered with the event source using a method
like addActionListener(), addMouseListener(), etc. This establishes the connection, so the event source
knows which listener to notify when an event happens.
Program:
import [Link].*;
import [Link];
import [Link];

public class MyFrame extends JFrame


{

private JButton myButton;


public MyFrame()
{
setTitle("Event Listener Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

myButton = new JButton("Click Me");


add(myButton);

// Create an instance of the ActionListener


ButtonClickListener listener = new ButtonClickListener();
// Register the listener with the button
[Link](listener);

setVisible(true);
}

// Inner class implementing ActionListener


private class ButtonClickListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
[Link]([Link], "Button Clicked!");
}
}

public static void main(String[] args)


{
new MyFrame();
}
}

Event Classes :-

In Java, event classes are central to handling events, particularly in Graphical User Interface (GUI)
applications developed using AWT or Swing. These classes represent different types of occurrences or
interactions that can happen within an application.

Core Principles:

 [Link]:

This is the root class for all event state objects in Java. All event classes inherit from EventObject, which
provides a fundamental structure for events, including a reference to the source object that generated the event.

 [Link]:
This class is the root for all AWT-specific events and their subclasses. It supersedes the
older [Link] class, which is now considered obsolete and maintained only for backward compatibility.
Common Event Classes (primarily from [Link] and [Link] packages):

 ActionEvent: Generated when a user performs an action, such as clicking a button, selecting a menu item, or
pressing Enter in a text field.
 MouseEvent: Triggered by mouse interactions like clicking, pressing, releasing, moving, or dragging the
mouse. It also includes events for the mouse wheel (MouseWheelEvent).

 KeyEvent: Generated when a key is pressed, released, or typed on the keyboard.

 FocusEvent: Occurs when a component gains or loses keyboard focus.

 ComponentEvent: Generated when a component is hidden, moved, resized, or becomes visible.

 ContainerEvent: Occurs when a component is added to or removed from a container.

 AdjustmentEvent: Generated when a scroll bar is manipulated.

 ItemEvent: Occurs when an item in a list, checkbox, or choice component is selected or deselected.

 WindowEvent: Relates to window-level events, such as opening, closing, iconifying, deiconifying, activating,
or deactivating a window.
Purpose:
Event classes encapsulate information about an event, allowing the application to respond
appropriately. When an event occurs, an object of the corresponding event class is created and dispatched to
registered event listeners, which then process the event based on its type and properties.

Handling mouse and keyboard events in Java:-

Handling mouse and keyboard events in Java involves using event listeners and adapter classes from
the [Link] package.

Handling Mouse Events:

Interfaces:
 MouseListener: For events like mouse clicks, presses, releases, entering, and exiting a component.

 MouseMotionListener: For events like mouse movement and dragging.


Implementation:
 Implement the desired interface(s) in your class.

 Override all abstract methods defined in the interface(s).

For example,

mouseClicked(MouseEvent e), mousePressed(MouseEvent e), mouseReleased(MouseEvent


e), mouseEntered(MouseEvent e), mouseExited(MouseEvent e) for MouseListener,
and mouseDragged(MouseEvent e), mouseMoved(MouseEvent e) for MouseMotionListener.

 Inside these methods, define the actions to be performed when the corresponding event occurs.

 Register the listener with the component that will generate the events
using addMouseListener(this) and/or addMouseMotionListener(this).
Adapter Classes (Optional):
 If you only need to handle a few specific mouse events, you can
extend MouseAdapter or MouseMotionAdapter instead of directly implementing the interfaces. This allows
you to override only the methods you need, avoiding the need to provide empty implementations for unused
methods.

Program: Example (MouseListener):

import [Link];
import [Link];
import [Link];
import [Link];

public class MouseEventHandler extends JFrame implements MouseListener


{
JLabel label;
public MouseEventHandler()
{
label = new JLabel("Move your mouse over here!");
add(label);
addMouseListener(this); // Register the listener
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

@Override
public void mouseClicked(MouseEvent e)
{
[Link]("Mouse Clicked at: " + [Link]() + ", " + [Link]());
}

@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed at: " + [Link]() + ", " + [Link]());
}

@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released at: " + [Link]() + ", " + [Link]());
}

@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered!");
}

@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited!");
}

public static void main(String[] args) {


new MouseEventHandler();
}
}
Handling Keyboard Events:

 Interface:
o KeyListener: For events like key presses, releases, and typing.
 Implementation:
o Implement the KeyListener interface in your class.

o Override its three abstract methods: keyPressed(KeyEvent e), keyReleased(KeyEvent e),


and keyTyped(KeyEvent e).

o Inside these methods, define the actions to be performed based on the key event. You can get the character
or key code of the pressed key using methods like [Link]() or [Link]().

o Register the listener with the component that will generate the events using addKeyListener(this). Note that
the component must be "focusable" for keyboard events to be captured.
Program Example (KeyListener):

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class KeyboardEventHandler extends JFrame implements KeyListener


{
JLabel label;

public KeyboardEventHandler()
{
JPanel panel = new JPanel();
label = new JLabel("Press any key!");
[Link](label);
add(panel);

addKeyListener(this); // Register the listener


setFocusable(true); // Make the frame focusable to receive key events
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

@Override
public void keyPressed(KeyEvent e)
{
[Link]("Key Pressed: " + [Link]([Link]()));
}

@Override
public void keyReleased(KeyEvent e)
{
[Link]("Key Released: " + [Link]([Link]()));
}

@Override
public void keyTyped(KeyEvent e)
{
[Link]("Key Typed: " + [Link]());
}

public static void main(String[] args)


{
new KeyboardEventHandler();
}
}
OutPut

Adapter classes in Java

Adapter classes in Java are abstract classes that provide empty, default implementations for all methods
defined in a corresponding listener interface. They are primarily used to simplify event handling in GUI
applications (like those built with AWT or Swing).

Purpose and Benefits:

 Simplifying Event Handling:

When you implement a listener interface directly, you are required to provide an implementation for all its
methods, even if you only care about a few specific events. Adapter classes eliminate this requirement.
 Reducing Boilerplate Code:

By extending an adapter class, you only need to override the methods corresponding to the events you want
to handle, significantly reducing the amount of boilerplate code needed.

 Enhanced Readability and Maintainability:


Concise code that focuses only on relevant event handling logic is easier to read and maintain.
How they work:
Instead of a class implements a listener interface (e.g., MouseListener), it extends the corresponding adapter
class (e.g., MouseAdapter). Then, only the specific methods related to the desired events are overridden in
the extending class.

Example:
Consider the MouseListener interface, which has multiple methods
like mousePressed(), mouseReleased(), mouseClicked(), mouseEntered(), and mouseExited(). If you only
want to handle a mousePressed event, using MouseAdapter simplifies the process:
JavaProgram

import [Link];
import [Link];

public class MyMouseHandler extends MouseAdapter


{
@Override
Public static void main(String ar[])

{ public void mousePressed(MouseEvent e)


{
[Link]("Mouse button pressed at: " + [Link]() + ", " + [Link]());
}
}
}

Java Inner Classes:-

In Java, it is also possible to nest classes (a class within a class). The purpose of nested classes is to group
classes that belong together, which makes your code more readable and maintainable.

To access the inner class, create an object of the outer class, and then create an object of the inner class:

Program:

class OuterClass
{
int x = 10;

class InnerClass
{
int y = 5;
}
}

public class Main


{
public static void main(String[] args)
{
OuterClass myOuter = new OuterClass();
[Link] myInner = [Link] InnerClass();
[Link](myInner.y + myOuter.x);
}
}

// Outputs 15 (5 + 10)

Private Inner Class:

Unlike a "regular" class, an inner class can be private or protected. If you don't want outside objects to
access the inner class, declare the class as private:

Example
class OuterClass
{
int x = 10;
private class InnerClass
{
int y = 5;
}
}
public class Main
{
public static void main(String[] args)
{
OuterClass myOuter = new OuterClass();
[Link] myInner = [Link] InnerClass();
[Link](myInner.y + myOuter.x);
}
}

OutPut:

Static Inner Class:-

An inner class can also be static, which means that you can access it without creating an object of the outer
class:
class OuterClass
{
int x = 10;

static class InnerClass


{
int y = 5;
}
}

public class Main


{
public static void main(String[] args)
{
[Link] myInner = new [Link]();
[Link](myInner.y);
}
}

// Outputs 5

Note: just like static attributes and methods, a static inner class does not have access to members of
the outer class.

Access Outer Class From Inner Class:-

One advantage of inner classes, is that they can access attributes and methods of the outer class:

class OuterClass
{
int x = 10;

class InnerClass
{
public int myInnerMethod()
{
return x;
}
}
}

public class Main


{
public static void main(String[] args)
{
OuterClass myOuter = new OuterClass();
[Link] myInner = [Link] InnerClass();
[Link]([Link]());
}
}

// Outputs 10
Anonymous Inner Class in Java
Nested Classes in Java is prerequisite required before adhering forward to grasp about anonymous Inner
class. It 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 overriding
methods of a class or interface, without having to actually subclass a class.
// Java program to demonstrate Need for
// Anonymous Inner class

interface Age
{
// Defining variables and methods
int x = 21;
void getAge();
}
class MyClass implements Age
{
@Override public void getAge()
{
// Print statement
[Link]("Age is " + x);
}
}

class GFG
{
public static void main(String[] args)
{
MyClass obj = new MyClass();
[Link]();
}
}

Output:
Age is 21
// Java Program to Demonstrate Anonymous inner class

// Interface
interface Age
{
int x = 21;
void getAge();
}

// Main class
class AnonymousDemo
{
public static void main(String[] args)
{
Age oj1 = new Age()
{
@Override public void getAge()
{
[Link]("Age is " + x);
}
}
[Link]();
}
}

Output: age is 21

Types of Anonymous Inner Class


Based on declaration and behavior, there are 3 types of anonymous Inner classes:
1. Anonymous Inner class that extends a class
2. Anonymous Inner class that implements an interface
3. Anonymous Inner class that defines inside method/constructor argument
Type 1: Anonymous Inner class that extends a class
We can have an anonymous inner class that extends a class. For example, we know
that we can create a thread by extending a Thread class. Suppose we need an
immediate thread but we don't want to create a class that extends Thread class all the
time. With the help of this type of Anonymous Inner class, we can define a ready
thread.
Example
// Java program to illustrate creating an immediate thread
// Using Anonymous Inner class that extends a Class

// Main class
class MyThread {

// Main driver method


public static void main(String[] args)
{
// Using Anonymous Inner class that extends a class
// Here a Thread class
Thread t = new Thread() {

// run() method for the thread


public void run()
{
// Print statement for child thread
// execution
[Link]("Child Thread");
}
};

// Starting the thread


[Link]();

// Displaying main thread only for readability


[Link]("Main Thread");
}
}

Output
Main Thread
Child Thread
Type 2: Anonymous Inner class that implements an interface
We can also have an anonymous inner class that implements an interface. For
example, we also know that by implementing Runnable interface we can create a
Thread. Here we use an anonymous Inner class that implements an interface.
Example
// Java program to illustrate defining a thread
// Using Anonymous Inner class that implements an interface

// Main class
class MyThread {

// Main driver method


public static void main(String[] args)
{
// Here we are using Anonymous Inner class
// that implements a interface i.e. Here Runnable
// interface
Runnable r = new Runnable() {

// run() method for the thread


public void run()
{
// Print statement when run() is invoked
[Link]("Child Thread");
}
};

// Creating thread in main() using Thread class


Thread t = new Thread(r);

// Starting the thread using start() method


// which invokes run() method automatically
[Link]();

// Print statement only


[Link]("Main Thread");
}
}

Output
Main Thread
Child Thread
Type 3: Anonymous Inner class that defines inside method/constructor argument
Anonymous inner classes in method/constructor arguments are often used in
graphical user interface (GUI) applications. To get you familiar with syntax lets have a
look at the following program that creates a thread using this type of Anonymous
Inner class
Example
// Java program to illustrate defining a thread
// Using Anonymous Inner class that define inside argument

// Main class
class MyThread {
// Main driver method
public static void main(String[] args)
{
// Using Anonymous Inner class that define inside
// argument
// Here constructor argument
Thread t = new Thread(new Runnable() {

public void run()


{
[Link]("Child Thread");
}
});

[Link]();
[Link]("Main Thread");
}
}

Output
Main Thread
Child Thread

You might also like