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

Understanding Java Nested Classes

The document explains nested classes in Java, which are classes defined within another class or interface, enhancing code organization and encapsulation. It categorizes nested classes into static nested classes, inner classes, method local inner classes, and anonymous inner classes, detailing their characteristics and usage with examples. The document emphasizes the benefits of using nested classes for better readability and maintainability of code.

Uploaded by

arunsnath44
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 views5 pages

Understanding Java Nested Classes

The document explains nested classes in Java, which are classes defined within another class or interface, enhancing code organization and encapsulation. It categorizes nested classes into static nested classes, inner classes, method local inner classes, and anonymous inner classes, detailing their characteristics and usage with examples. The document emphasizes the benefits of using nested classes for better readability and maintainability of code.

Uploaded by

arunsnath44
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

NESTED CLASS

The Java programming language allows you to define a class within another class or interface. Such a
class is called a nested class. The class in which nested class declared is called outer class.

We use inner classes to logically group classes and interfaces in one place to be more readable and
maintainable. It can access all the members of the outer class, including private data members and
methods.

Nested classes can also be used to create nested data structures, such as a linked list. Nested data
structures can be more efficient than flat data structures and can lead to better code organization.

 It is a way of logically grouping classes that are only used in one place: If a class is useful to
only one other class, then it is logical to embed it in that class and keep the two together. Nesting
such "helper classes" makes their package more streamlined.
 It increases encapsulation: Consider two top-level classes, A and B, where B needs access to
members of A that would otherwise be declared private. By hiding class B within class A, A's
members can be declared private and B can access them. In addition, B itself can be hidden from
the outside world.
 It can lead to more readable and maintainable code: Nesting small classes within top-level
classes places the code closer to where it is used.

Nested classes are divided into two categories: non-static and static. Non-static nested classes are
called inner classes. Nested classes that are declared static are called static nested classes.

1. Static Nested Class


These are the simplest type of inner classes. Static inner classes are those that are declared inside a
class and marked static. Static nested classes can access only static members of the outer class. A
static nested class is the same as any other top-level class. Can access the class without having to
create an object of the outer class.

[Link] nestedObject =

new [Link]();

Eg:

class MotherBoard {
int usb1=5;
static int usb2 = 2;
static class USB{
int usb3 = 1;
int getTotalPorts()
{
return usb2 + usb3;
}
}

}
public class Main {
public static void main(String[] args) {
// create an object of the static nested class
[Link] usb = new [Link]();
[Link]("Total Ports = " + [Link]());
}
}
Run Code
Output:

Total Ports = 3
2. Inner Class (Member Inner Class)
An inner class is associated with an instance of its enclosing class and has direct access to that
object's methods and fields. Also, because an inner class is associated with an instance, it cannot
define any static members itself. An inner class can be private and once you declare an inner class
private, it cannot be accessed from an object outside the class.

An instance of InnerClass can exist only within an instance of OuterClass.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object
within the outer object with this syntax:

OuterClass outerObject = new OuterClass();

[Link] innerObject = [Link] InnerClass();

Eg:

class Car {
String carName;
String carType;
public Car(String name, String type) {
[Link] = name;
[Link] = type;
}
private String getCarName() {
return [Link];
}
class Engine { // inner class
String engineType;
void setEngine() {

// Accessing the carType property of Car


if([Link]("4WD"))
{
if([Link]().equals("Crysler"))
{
[Link] = "Smaller";
}
else {
[Link] = "Bigger";
}

}
else{
[Link] = "Bigger";
}
}
String getEngineType(){
return [Link];
}
}
}

public class Main {


public static void main(String[] args) {

Car car1 = new Car("Mazda", "8WD");


// create an object of inner class using the outer class
[Link] engine = [Link] Engine();
[Link]();
[Link]("Engine Type for 8WD= " + [Link]());

Car car2 = new Car("Crysler", "4WD");


[Link] c2engine = [Link] Engine();
[Link]();
[Link]("Engine Type for 4WD = " + [Link]());
}
}
Output:

Engine Type for 8WD= Bigger


Engine Type for 4WD = Smaller
3. Method Local Inner Class(Local Inner Class)
A class created inside a method is called local inner class in java. A method local inner class is
accessible only within the method in which it was defined, and cannot be referenced by any other
code outside the method in which it is defined. A method local inner class can access local variables
from the enclosing scope (including final variables).

Eg:
class OuterClass {
void outerClassMethod()
{
final String site = "[Link]";
[Link]("Hey I am inside outerClassMethod");
class InnerClass // method inner class
{
void innerClassMethod() {
[Link]("I am studying Java at " + site);
}
} //method inner class closed
InnerClass in =new InnerClass();
in .innerClassMethod(); //calling method of inner class
}
}

public class MainClass {


public static void main(String[] args) {
OuterClass out = new OuterClass();
[Link]();
}
}
Output
Hey I am inside outerClassMethod
I am studying Java at [Link]

4. 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. we declare and instantiate them at the same time. Anonymous inner classes are accessible
only at the point where it is defined

Java Anonymous inner class can be created in two ways:

 Class or interface(may be abstract or concrete).


The anonymous class is put inside a subclass of the outer class without a name.
Eg:
abstract class Person
{
abstract void eat();
}
class TestAnonymousInner
{
public static void main(String args[])
{
Person p=new Person() {
void eat(){[Link]("nice fruits");} //anonymous class
};
[Link]();
}
}
Output:
nice fruits
 Anonymous Inner Class as Argument
if a method accepts an object of an interface, an abstract class, or a concrete class you can
pass an anonymous inner class to the method.
Eg:
interface Message
{
String greet();
}

public class My_class {


// method which accepts the object of interface Message
public void displayMessage(Message m)
{
[Link]([Link]() + ", This is an example of anonymous inner class as an
argument");
}
}
Public class Abc{
public static void main(String args[])
{
My_class obj = new My_class();
// Passing an anonymous inner class as an argument
[Link](new Message() {
public String greet() {
return "Hello";
}
});
}
}
Output:
Hello, This is an example of anonymous inner class as an argument

You might also like