SlideShare ist ein Scribd-Unternehmen logo
1 von 9
1
Nested Classes
The Java programming language allows you to define a class within another class. Such a
class is called a nested class and is illustrated here:
class OuterClass {
...
class NestedClass {
...
}
}
Nested classes are divided into two categories:
1. Static
2. Non-static.
Nested classes that are declared static are called static nested classes.
Non-static nested classes are called inner classes.
class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
A nested class is a member of its enclosing class. Non-static nested classes (inner classes)
have access to other members of the enclosing class, even if they are declared private. Static
nested classes do not have access to other members of the enclosing class. As a member of
the OuterClass, a nested class can be declared private, public,protected, or package private.
2
Why Use Nested Classes?
Compelling reasons for using nested classes include the following:
1. 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.
2. 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.
3. 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.
Static Nested Classes
As with class methods and variables, a static nested class is associated with its outer class.
And like static class methods, a static nested class cannot refer directly to instance variables
or methods defined in its enclosing class: it can use them only through an object reference.
Note: A static nested class interacts with the instance members of its outer class (and other
classes) just like any other top-level class. In effect, a static nested class is behaviourally a
top-level class that has been nested in another top-level class for packaging convenience.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
3
The following code excerpt shows how static nested classes are defined, how they access the
the private members of their enclosing class (only via the use of an object instance) and how
to obtain an instance a static nested class:
class StaticInner{
static class Inner{
void inn(){
System.out.println("inner");
}
}
public static void main(String args[]){
Inner ob = new Inner();
ob.inn();
}
}
Non-Static Nested Class
Inner Classes
As with instance methods and variables, 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.
Objects that are instances of an inner class exist within an instance of the outer class.
Consider the following classes:
class OuterClass {
...
class InnerClass {
...
}
4
}
1. An instance of InnerClass can exist only within an instance of OuterClass and has
direct access to the methods and fields of its enclosing instance.
2. To instantiate an inner class, you must first instantiate the outer class. Then, create the
inner object within the outer object with this syntax:
3. OuterClass.InnerClass innerObject = outerObject.new InnerClass();
4. There are three kinds of inner classes: Member inner class, local inner
classes and anonymous inner classes.
A. Member inner class
Member inner classes are treated as a member of an outer class.
Member Inner class can be accessed only through live instance of outer class.
Outer class can create instance of the inner class in the same way as normal class member.
Member inner class will be treated like member of the outer class so it can have several
Modifiers as opposed to Class.
o final
o abstract
o public
o private
o protected
Created As Below:
class OuterClass {
...
class InnerClass {
...
}
}
5
Example:
class Outer{
void out(){
System.out.println("outer");
Inner ob = new Inner();
ob.inn();
}
class Inner{
void inn(){
System.out.println("inner");
}
}
}
class MemberInner{
public static void main(String args[]){
Outer ob= new Outer();
ob.out();
}
}
6
B. Local inner class
1. Local classes are classes that are defined in a block, which is a group of zero or more
statements between balanced braces. You typically find local classes defined in the
body of a method.
2. You can define a local class inside any block. For example, you can define a local
class in a method body, a for loop, or an ifclause.
3. A local class has access to the members of its enclosing class.
4. A local class has access to local variables. However, a local class can only access
local variables that are declared final. Local classes in static methods, such as the
class , which is defined in the static method can only refer to static members of the
enclosing class
Example:
class Outer{
void out(){
class Inner
{
void inn(){
System.out.println("inner");
}
}
System.out.println("outer");
Inner ob = new Inner();
ob.inn();
}
}
class LocalInner
7
{
public static void main(String args[])
{
Outer ob= new Outer();
ob.out();
}
}
C. Anonymous inner class
1. Anonymous classes enable you to make your code more concise. They
enable you to declare and instantiate a class at the same time. They are like
local classes except that they do not have a name. Use them if you need to
use a local class only once.
2. While local classes are class declarations, anonymous classes are
expressions, which means that you define the class in another expression
3. Anonymous classes have the same access to local variables of the enclosing
scope as local classes:
a. An anonymous class has access to the members of its enclosing class.
b. An anonymous class cannot access local variables in its enclosing scope
that are not declared as final or effectively final.
4. Anonymous classes also have the same restrictions as local classes with
respect to their members:
a. You cannot declare static initializers or member interfaces in an
anonymous class.
b. An anonymous class can have static members provided that they are
constant variables.
Example:
8
abstract class Outeranon{
abstract void display();
}
class AnonymousInner{
public static void main(String args[]){
Outeranon ob =new Outeranon(){
void display()
{
System.out.println("inner");
}
};
ob.display();
}
}
9
REFRENCES
[1]The Complete Refrence JAVA by Herbert Schildt, TATA McGRAW-HILL publication.
[2] http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html

Weitere ähnliche Inhalte

Was ist angesagt? (18)

Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVA
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
 
C# Inheritance
C# InheritanceC# Inheritance
C# Inheritance
 
Inner Classes
Inner ClassesInner Classes
Inner Classes
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
Nested classes in java
Nested classes in javaNested classes in java
Nested classes in java
 
C# Access modifiers
C# Access modifiersC# Access modifiers
C# Access modifiers
 
Inner Classes in Java
Inner Classes in JavaInner Classes in Java
Inner Classes in Java
 
Inner class
Inner classInner class
Inner class
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Java Nested class Concept
Java Nested class ConceptJava Nested class Concept
Java Nested class Concept
 
types of classes in java
types of classes in javatypes of classes in java
types of classes in java
 
[圣思园][Java SE]Inner class
[圣思园][Java SE]Inner class[圣思园][Java SE]Inner class
[圣思园][Java SE]Inner class
 
Classes
ClassesClasses
Classes
 
Access specifier
Access specifierAccess specifier
Access specifier
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 

Ähnlich wie Nested classes in java

A1771937735_21789_14_2018__16_ Nested Classes.ppt
A1771937735_21789_14_2018__16_ Nested Classes.pptA1771937735_21789_14_2018__16_ Nested Classes.ppt
A1771937735_21789_14_2018__16_ Nested Classes.pptRithwikRanjan
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
Object oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxObject oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxDaveEstonilo
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#foreverredpb
 
Inner classes9 cm604.28
Inner classes9 cm604.28Inner classes9 cm604.28
Inner classes9 cm604.28myrajendra
 
type of class in c#
type of class in c#type of class in c#
type of class in c#tahria123
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptmanomkpsg
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfbca23189c
 
Chapter18 class-and-objects
Chapter18 class-and-objectsChapter18 class-and-objects
Chapter18 class-and-objectsDeepak Singh
 
this keyword in Java.pdf
this keyword in Java.pdfthis keyword in Java.pdf
this keyword in Java.pdfParvizMirzayev2
 

Ähnlich wie Nested classes in java (20)

A1771937735_21789_14_2018__16_ Nested Classes.ppt
A1771937735_21789_14_2018__16_ Nested Classes.pptA1771937735_21789_14_2018__16_ Nested Classes.ppt
A1771937735_21789_14_2018__16_ Nested Classes.ppt
 
Nested class
Nested classNested class
Nested class
 
Inner class
Inner classInner class
Inner class
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Object oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxObject oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptx
 
Javasession8
Javasession8Javasession8
Javasession8
 
4 Classes & Objects
4 Classes & Objects4 Classes & Objects
4 Classes & Objects
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
Static Members-Java.pptx
Static Members-Java.pptxStatic Members-Java.pptx
Static Members-Java.pptx
 
C# Types of classes
C# Types of classesC# Types of classes
C# Types of classes
 
Inner classes9 cm604.28
Inner classes9 cm604.28Inner classes9 cm604.28
Inner classes9 cm604.28
 
type of class in c#
type of class in c#type of class in c#
type of class in c#
 
Lecture 10
Lecture 10Lecture 10
Lecture 10
 
java tutorial 4
 java tutorial 4 java tutorial 4
java tutorial 4
 
inheritance
inheritanceinheritance
inheritance
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
 
Chapter18 class-and-objects
Chapter18 class-and-objectsChapter18 class-and-objects
Chapter18 class-and-objects
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
this keyword in Java.pdf
this keyword in Java.pdfthis keyword in Java.pdf
this keyword in Java.pdf
 

Mehr von Richa Singh

Fluid Simulation In Computer Graphics
Fluid Simulation In Computer GraphicsFluid Simulation In Computer Graphics
Fluid Simulation In Computer GraphicsRicha Singh
 
Load balancing in Distributed Systems
Load balancing in Distributed SystemsLoad balancing in Distributed Systems
Load balancing in Distributed SystemsRicha Singh
 
Google LOON Project
Google LOON ProjectGoogle LOON Project
Google LOON ProjectRicha Singh
 
Load Balancing In Distributed Computing
Load Balancing In Distributed ComputingLoad Balancing In Distributed Computing
Load Balancing In Distributed ComputingRicha Singh
 
Virtual Private Network
Virtual Private NetworkVirtual Private Network
Virtual Private NetworkRicha Singh
 
DLNA- DIGITAL LIVING NETWORK ALLIANCE
DLNA- DIGITAL LIVING NETWORK ALLIANCEDLNA- DIGITAL LIVING NETWORK ALLIANCE
DLNA- DIGITAL LIVING NETWORK ALLIANCERicha Singh
 
Google's LOON Project
Google's LOON ProjectGoogle's LOON Project
Google's LOON ProjectRicha Singh
 

Mehr von Richa Singh (8)

Fluid Simulation In Computer Graphics
Fluid Simulation In Computer GraphicsFluid Simulation In Computer Graphics
Fluid Simulation In Computer Graphics
 
Load balancing in Distributed Systems
Load balancing in Distributed SystemsLoad balancing in Distributed Systems
Load balancing in Distributed Systems
 
Google LOON Project
Google LOON ProjectGoogle LOON Project
Google LOON Project
 
Load Balancing In Distributed Computing
Load Balancing In Distributed ComputingLoad Balancing In Distributed Computing
Load Balancing In Distributed Computing
 
Virtual Private Network
Virtual Private NetworkVirtual Private Network
Virtual Private Network
 
DLNA- DIGITAL LIVING NETWORK ALLIANCE
DLNA- DIGITAL LIVING NETWORK ALLIANCEDLNA- DIGITAL LIVING NETWORK ALLIANCE
DLNA- DIGITAL LIVING NETWORK ALLIANCE
 
Html Basic Tags
Html Basic TagsHtml Basic Tags
Html Basic Tags
 
Google's LOON Project
Google's LOON ProjectGoogle's LOON Project
Google's LOON Project
 

Kürzlich hochgeladen

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 

Kürzlich hochgeladen (20)

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 

Nested classes in java

  • 1. 1 Nested Classes The Java programming language allows you to define a class within another class. Such a class is called a nested class and is illustrated here: class OuterClass { ... class NestedClass { ... } } Nested classes are divided into two categories: 1. Static 2. Non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes. class OuterClass { ... static class StaticNestedClass { ... } class InnerClass { ... } } A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private, public,protected, or package private.
  • 2. 2 Why Use Nested Classes? Compelling reasons for using nested classes include the following: 1. 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. 2. 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. 3. 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. Static Nested Classes As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference. Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviourally a top-level class that has been nested in another top-level class for packaging convenience. Static nested classes are accessed using the enclosing class name: OuterClass.StaticNestedClass For example, to create an object for the static nested class, use this syntax: OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
  • 3. 3 The following code excerpt shows how static nested classes are defined, how they access the the private members of their enclosing class (only via the use of an object instance) and how to obtain an instance a static nested class: class StaticInner{ static class Inner{ void inn(){ System.out.println("inner"); } } public static void main(String args[]){ Inner ob = new Inner(); ob.inn(); } } Non-Static Nested Class Inner Classes As with instance methods and variables, 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. Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes: class OuterClass { ... class InnerClass { ... }
  • 4. 4 } 1. An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. 2. To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: 3. OuterClass.InnerClass innerObject = outerObject.new InnerClass(); 4. There are three kinds of inner classes: Member inner class, local inner classes and anonymous inner classes. A. Member inner class Member inner classes are treated as a member of an outer class. Member Inner class can be accessed only through live instance of outer class. Outer class can create instance of the inner class in the same way as normal class member. Member inner class will be treated like member of the outer class so it can have several Modifiers as opposed to Class. o final o abstract o public o private o protected Created As Below: class OuterClass { ... class InnerClass { ... } }
  • 5. 5 Example: class Outer{ void out(){ System.out.println("outer"); Inner ob = new Inner(); ob.inn(); } class Inner{ void inn(){ System.out.println("inner"); } } } class MemberInner{ public static void main(String args[]){ Outer ob= new Outer(); ob.out(); } }
  • 6. 6 B. Local inner class 1. Local classes are classes that are defined in a block, which is a group of zero or more statements between balanced braces. You typically find local classes defined in the body of a method. 2. You can define a local class inside any block. For example, you can define a local class in a method body, a for loop, or an ifclause. 3. A local class has access to the members of its enclosing class. 4. A local class has access to local variables. However, a local class can only access local variables that are declared final. Local classes in static methods, such as the class , which is defined in the static method can only refer to static members of the enclosing class Example: class Outer{ void out(){ class Inner { void inn(){ System.out.println("inner"); } } System.out.println("outer"); Inner ob = new Inner(); ob.inn(); } } class LocalInner
  • 7. 7 { public static void main(String args[]) { Outer ob= new Outer(); ob.out(); } } C. Anonymous inner class 1. Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once. 2. While local classes are class declarations, anonymous classes are expressions, which means that you define the class in another expression 3. Anonymous classes have the same access to local variables of the enclosing scope as local classes: a. An anonymous class has access to the members of its enclosing class. b. An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final. 4. Anonymous classes also have the same restrictions as local classes with respect to their members: a. You cannot declare static initializers or member interfaces in an anonymous class. b. An anonymous class can have static members provided that they are constant variables. Example:
  • 8. 8 abstract class Outeranon{ abstract void display(); } class AnonymousInner{ public static void main(String args[]){ Outeranon ob =new Outeranon(){ void display() { System.out.println("inner"); } }; ob.display(); } }
  • 9. 9 REFRENCES [1]The Complete Refrence JAVA by Herbert Schildt, TATA McGRAW-HILL publication. [2] http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html