SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVA
Tech_MX
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
Ravi_Kant_Sahu
 
Inner Classes
Inner ClassesInner Classes
Inner Classes
parag
 
[圣思园][Java SE]Inner class
[圣思园][Java SE]Inner class[圣思园][Java SE]Inner class
[圣思园][Java SE]Inner class
ArBing Xie
 

La actualidad más candente (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
 

Similar a Nested classes in java

Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
backdoor
 
Java Programming inner and Nested classes.pptx
Java Programming inner and Nested classes.pptxJava Programming inner and Nested classes.pptx
Java Programming inner and Nested classes.pptx
AkashJha84
 
Inner classes9 cm604.28
Inner classes9 cm604.28Inner classes9 cm604.28
Inner classes9 cm604.28
myrajendra
 
Chapter18 class-and-objects
Chapter18 class-and-objectsChapter18 class-and-objects
Chapter18 class-and-objects
Deepak Singh
 

Similar a 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
 
Java Programming inner and Nested classes.pptx
Java Programming inner and Nested classes.pptxJava Programming inner and Nested classes.pptx
Java Programming inner and Nested classes.pptx
 
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
 

Más de Richa Singh

Más de 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
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Último (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 

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