SlideShare a Scribd company logo
Programming in Java
Nested Classes
Contents
• Nested Class
• Static Nested Class
• Inner Class
• Local Class
• Anonymous Class
Nested/Inner Class
• The Java programming language allows us to define
a class within another class. Such a class is
called a nested class.
Example:
class OuterClass
{
...
class NestedClass
{
...
}
}
Advantages of Java Inner Classes
1) Nested classes represent a special type of
relationship that is it can access all the
members (data members and methods) of
outer class including private.
2) Nested classes are used to develop more
readable and maintainable code because it
logically group classes and interfaces in one
place only.
3) Code Optimization: It requires less code to
write.
Types of Nested Classes
• A nested class is a member of its enclosing class.
• Nested classes are divided into two categories:
– Static
– Non-Static
• Nested classes that are declared static are simply
called static nested classes.
• Non-static nested classes are called Inner classes.
Why Use Nested Classes?
• Logical grouping of classes —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.
• Increased 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.
• More readable, maintainable code —Nesting small classes
within top-level classes places the code closer to where it is
used.
Static Nested Classes
• A static class i.e. created inside a class is called
static nested class in java. It cannot access non-
static data members and methods. It can be
accessed by outer class name.
• It can access static data members of outer class
including private.
• Static nested class cannot access non-static
(instance) data member or method.
Static Nested Classes
• A static nested class is associated with its outer class similar
to class methods and variables.
• 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.
• 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();
class TestOuter1
{
static int data=30;
static class Inner
{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[])
{
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
} Output: data is 30
Inner Classes
• An inner class is associated with an instance of its enclosing
class and has direct access to that object's methods and
fields.
• 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 { ... }
}
• 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.
• To instantiate an inner class, we must first instantiate the
outer class. Then, create the inner object within the outer
object.
• Syntax:
OuterClass.InnerClass innerObject =
outerObject.new InnerClass();
class TestMemberOuter1
{
private int data=30;
class Inner
{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[])
{
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
• Additionally, there are two special kinds of inner
classes:
– Local Classes and
– Anonymous Classes (also called anonymous inner
classes).
Local Classes
• A class i.e. created inside a method is called local inner class in
java. If you want to invoke the methods of local inner class, you
must instantiate this class inside the method.
• Local classes are classes that are defined in a block, which is a
group of zero or more statements between balanced braces.
• For example, we can define a local class in a method body, a for
loop, or an if clause.
• A local class has access to the members of its enclosing class.
• A local class has access to local variables. However, a local class
can only access local variables that are declared final.
Important
• A local class has access to local variables. However, a
local class can only access local variables that are
declared final.
• Starting in Java SE 8, a local class can access local
variables and parameters of the enclosing block that are
final or effectively final.
• A variable or parameter whose value is never changed
after it is initialized is effectively final.
public class localInner1
{
private int data=30;//instance variable
void display(){
class Local
{
void msg(){System.out.println(data);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
localInner1 obj=new localInner1();
obj.display();
}
}
Rules for Local Inner Class
• Local variable can't be private, public or protected.
• Local inner class cannot be invoked from outside the
method.
• Local inner class cannot access non-final local
variable till JDK 1.7. Since JDK 1.8, it is possible to
access the non-final local variable in local inner
class.
Anonymous Classes
• A class that have no name is known as
anonymous inner class in java. It should
be used if you have to override method of
class or interface. Java Anonymous inner
class can be created by two ways:
1. Class (may be abstract or concrete).
2. Interface
Anonymous Classes
• Anonymous classes enable us to declare and instantiate a
class at the same time.
• They are like local classes except that they do not have a
name.
• The anonymous class expression consists of the following:
1. The new operator
2. The name of an interface to implement or a class to extend.
3. Parentheses that contain the arguments to a constructor,
just like a normal class instance creation expression.
4. A body, which is a class declaration body. More specifically,
in the body, method declarations are allowed but statements
are not.
 Anonymous classes have the same access to local variables of the
enclosing scope as local classes:
• An anonymous class has access to the members of its enclosing class.
• An anonymous class cannot access local variables in its enclosing scope
that are not declared as final.
 Anonymous classes also have the same restrictions as local classes
with respect to their members:
• We cannot declare static initializers or member interfaces in an anonymous
class.
• An anonymous class can have static members provided that they are
constant variables.
 Note that we can declare the following in anonymous classes:
• Fields
• Extra methods (even if they do not implement any methods of the
supertype)
• Local classes
• We cannot declare constructors in an anonymous class.
abstract class Person
{
abstract void eat();
}
class TestAnonymousInner
{
public static void main(String args[])
{ // Inside a method(main) only, Anonymous class is declared
Person p=new Person() //Statement do not end with
semicolon(as we cant create object for abstract class or interface)
{
void eat(){System.out.println("nice fruits");} Anonymous Inner Class
(only body is there without
identity)
};
p.eat();
}
}
• Generation of class Files:
• Person.class
• Person $ 1.class (For Anonymous class,
as they don’t have any name,
automatically no's will be assigned)
• Internal working of given code
Person p=new Person()
{
void eat(){System.out.println("nice fruits");}
};
• A class is created but its name is decided by the compiler
which extends the Person class and provides the
implementation of the eat() method.
• An object of Anonymous class is created that is referred by p
reference variable of Person type.
interface Eatable
{
void eat();
}
class TestAnnonymousInner1
{
public static void main(String args[])
{
Eatable e=new Eatable() //No Semicolon
{
public void eat(){System.out.println("nice fruits");}
};
e.eat();
}
}
Note:
When we compile a nested class, two different class files
will be created with names
Outerclass.class
Outerclass$Nestedclass.class
• Local Class is named as Outerclass$1Localclass.class
• Anonymous class is named as Outerclass$1.class
A1771937735_21789_14_2018__16_ Nested Classes.ppt

More Related Content

DOCX
Nested classes in java
PPTX
Java Programming inner and Nested classes.pptx
PPTX
Java Nested class Concept
PDF
Inner Classes in Java
DOCX
Nested class in java
PPTX
WINSEMFRE2024-25_CSE2005_ETH_AP2024255000715_2025-03-18_Reference-Material-I....
PPTX
Nested class
PPTX
Nested classes in java
Nested classes in java
Java Programming inner and Nested classes.pptx
Java Nested class Concept
Inner Classes in Java
Nested class in java
WINSEMFRE2024-25_CSE2005_ETH_AP2024255000715_2025-03-18_Reference-Material-I....
Nested class
Nested classes in java

Similar to A1771937735_21789_14_2018__16_ Nested Classes.ppt (20)

PPTX
Inner classes in java
PPTX
Inner class
PPTX
Javasession8
PPTX
Inner Classes & Multi Threading in JAVA
PPTX
Java Nested classes, static class and methods, nested blocks_Inner_Classes.pptx
PPTX
Inner classes
PPTX
types of classes in java
PPTX
Java- Nested Classes
PPTX
Inner class
PPTX
Object oriented programming CLASSES-AND-OBJECTS.pptx
PDF
Java Inner Classes
PPT
Inner classes ,annoumous and outer classes in java
PPTX
Static Members-Java.pptx
PPT
L5 classes, objects, nested and inner class
PPT
Inner classes9 cm604.28
PDF
Classes in Java great learning.pdf
PPTX
Java Inner Class
PPTX
Session 21 - Inner Classes
PDF
Java Inner Classes
PPSX
Inner Classes
Inner classes in java
Inner class
Javasession8
Inner Classes & Multi Threading in JAVA
Java Nested classes, static class and methods, nested blocks_Inner_Classes.pptx
Inner classes
types of classes in java
Java- Nested Classes
Inner class
Object oriented programming CLASSES-AND-OBJECTS.pptx
Java Inner Classes
Inner classes ,annoumous and outer classes in java
Static Members-Java.pptx
L5 classes, objects, nested and inner class
Inner classes9 cm604.28
Classes in Java great learning.pdf
Java Inner Class
Session 21 - Inner Classes
Java Inner Classes
Inner Classes
Ad

More from RithwikRanjan (13)

PPTX
INTERNSHIP PRESENTATION.pptx
PPTX
internship.pptx
PPTX
AM.pptx
PPT
4_A1208223655_21789_2_2018_04. Operators.ppt
PPTX
sam_technical_seminar.pptx
PPTX
sam_report.pptx
PPTX
TQM-Module 5.pptx
PPTX
CIM MODULE 2.pptx
PPT
A2003822018_21789_17_2018_09. ArrayList.ppt
PPT
0_A1590026209_21789_20_2018_0 Lecture.ppt
PPT
A457405934_21789_26_2018_Inheritance.ppt
PPT
6_A1944859510_21789_2_2018_06. Branching Statements.ppt
PPT
A1869984431_21789_28_2018_Abstract Class.ppt
INTERNSHIP PRESENTATION.pptx
internship.pptx
AM.pptx
4_A1208223655_21789_2_2018_04. Operators.ppt
sam_technical_seminar.pptx
sam_report.pptx
TQM-Module 5.pptx
CIM MODULE 2.pptx
A2003822018_21789_17_2018_09. ArrayList.ppt
0_A1590026209_21789_20_2018_0 Lecture.ppt
A457405934_21789_26_2018_Inheritance.ppt
6_A1944859510_21789_2_2018_06. Branching Statements.ppt
A1869984431_21789_28_2018_Abstract Class.ppt
Ad

Recently uploaded (20)

PDF
YOW2022-BNE-MinimalViableArchitecture.pdf
PPTX
YV PROFILE PROJECTS PROFILE PRES. DESIGN
PPT
Machine printing techniques and plangi dyeing
DOCX
actividad 20% informatica microsoft project
PPTX
rapid fire quiz in your house is your india.pptx
PDF
Integrated-2D-and-3D-Animation-Bridging-Dimensions-for-Impactful-Storytelling...
PDF
Interior Structure and Construction A1 NGYANQI
PDF
GREEN BUILDING MATERIALS FOR SUISTAINABLE ARCHITECTURE AND BUILDING STUDY
PPT
UNIT I- Yarn, types, explanation, process
PPTX
ANATOMY OF ANTERIOR CHAMBER ANGLE AND GONIOSCOPY.pptx
PPTX
Media And Information Literacy for Grade 12
PPTX
Special finishes, classification and types, explanation
PPTX
joggers park landscape assignment bandra
PDF
UNIT 1 Introduction fnfbbfhfhfbdhdbdto Java.pptx.pdf
PPTX
Wisp Textiles: Where Comfort Meets Everyday Style
PPTX
BSCS lesson 3.pptxnbbjbb mnbkjbkbbkbbkjb
PDF
Quality Control Management for RMG, Level- 4, Certificate
PPTX
An introduction to AI in research and reference management
PPTX
AC-Unit1.pptx CRYPTOGRAPHIC NNNNFOR ALL
PPTX
building Planning Overview for step wise design.pptx
YOW2022-BNE-MinimalViableArchitecture.pdf
YV PROFILE PROJECTS PROFILE PRES. DESIGN
Machine printing techniques and plangi dyeing
actividad 20% informatica microsoft project
rapid fire quiz in your house is your india.pptx
Integrated-2D-and-3D-Animation-Bridging-Dimensions-for-Impactful-Storytelling...
Interior Structure and Construction A1 NGYANQI
GREEN BUILDING MATERIALS FOR SUISTAINABLE ARCHITECTURE AND BUILDING STUDY
UNIT I- Yarn, types, explanation, process
ANATOMY OF ANTERIOR CHAMBER ANGLE AND GONIOSCOPY.pptx
Media And Information Literacy for Grade 12
Special finishes, classification and types, explanation
joggers park landscape assignment bandra
UNIT 1 Introduction fnfbbfhfhfbdhdbdto Java.pptx.pdf
Wisp Textiles: Where Comfort Meets Everyday Style
BSCS lesson 3.pptxnbbjbb mnbkjbkbbkbbkjb
Quality Control Management for RMG, Level- 4, Certificate
An introduction to AI in research and reference management
AC-Unit1.pptx CRYPTOGRAPHIC NNNNFOR ALL
building Planning Overview for step wise design.pptx

A1771937735_21789_14_2018__16_ Nested Classes.ppt

  • 2. Contents • Nested Class • Static Nested Class • Inner Class • Local Class • Anonymous Class
  • 3. Nested/Inner Class • The Java programming language allows us to define a class within another class. Such a class is called a nested class. Example: class OuterClass { ... class NestedClass { ... } }
  • 4. Advantages of Java Inner Classes 1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private. 2) Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only. 3) Code Optimization: It requires less code to write.
  • 5. Types of Nested Classes • A nested class is a member of its enclosing class. • Nested classes are divided into two categories: – Static – Non-Static • Nested classes that are declared static are simply called static nested classes. • Non-static nested classes are called Inner classes.
  • 6. Why Use Nested Classes? • Logical grouping of classes —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. • Increased 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. • More readable, maintainable code —Nesting small classes within top-level classes places the code closer to where it is used.
  • 7. Static Nested Classes • A static class i.e. created inside a class is called static nested class in java. It cannot access non- static data members and methods. It can be accessed by outer class name. • It can access static data members of outer class including private. • Static nested class cannot access non-static (instance) data member or method.
  • 8. Static Nested Classes • A static nested class is associated with its outer class similar to class methods and variables. • 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. • 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();
  • 9. class TestOuter1 { static int data=30; static class Inner { void msg(){System.out.println("data is "+data);} } public static void main(String args[]) { TestOuter1.Inner obj=new TestOuter1.Inner(); obj.msg(); } } Output: data is 30
  • 10. Inner Classes • An inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. • 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 { ... } }
  • 11. • 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. • To instantiate an inner class, we must first instantiate the outer class. Then, create the inner object within the outer object. • Syntax: OuterClass.InnerClass innerObject = outerObject.new InnerClass();
  • 12. class TestMemberOuter1 { private int data=30; class Inner { void msg(){System.out.println("data is "+data);} } public static void main(String args[]) { TestMemberOuter1 obj=new TestMemberOuter1(); TestMemberOuter1.Inner in=obj.new Inner(); in.msg(); } }
  • 13. • Additionally, there are two special kinds of inner classes: – Local Classes and – Anonymous Classes (also called anonymous inner classes).
  • 14. Local Classes • A class i.e. created inside a method is called local inner class in java. If you want to invoke the methods of local inner class, you must instantiate this class inside the method. • Local classes are classes that are defined in a block, which is a group of zero or more statements between balanced braces. • For example, we can define a local class in a method body, a for loop, or an if clause. • A local class has access to the members of its enclosing class. • A local class has access to local variables. However, a local class can only access local variables that are declared final.
  • 15. Important • A local class has access to local variables. However, a local class can only access local variables that are declared final. • Starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. • A variable or parameter whose value is never changed after it is initialized is effectively final.
  • 16. public class localInner1 { private int data=30;//instance variable void display(){ class Local { void msg(){System.out.println(data);} } Local l=new Local(); l.msg(); } public static void main(String args[]){ localInner1 obj=new localInner1(); obj.display(); } }
  • 17. Rules for Local Inner Class • Local variable can't be private, public or protected. • Local inner class cannot be invoked from outside the method. • Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access the non-final local variable in local inner class.
  • 18. Anonymous Classes • A class that have no name is known as anonymous inner class in java. It should be used if you have to override method of class or interface. Java Anonymous inner class can be created by two ways: 1. Class (may be abstract or concrete). 2. Interface
  • 19. Anonymous Classes • Anonymous classes enable us to declare and instantiate a class at the same time. • They are like local classes except that they do not have a name. • The anonymous class expression consists of the following: 1. The new operator 2. The name of an interface to implement or a class to extend. 3. Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. 4. A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
  • 20.  Anonymous classes have the same access to local variables of the enclosing scope as local classes: • An anonymous class has access to the members of its enclosing class. • An anonymous class cannot access local variables in its enclosing scope that are not declared as final.  Anonymous classes also have the same restrictions as local classes with respect to their members: • We cannot declare static initializers or member interfaces in an anonymous class. • An anonymous class can have static members provided that they are constant variables.  Note that we can declare the following in anonymous classes: • Fields • Extra methods (even if they do not implement any methods of the supertype) • Local classes • We cannot declare constructors in an anonymous class.
  • 21. abstract class Person { abstract void eat(); } class TestAnonymousInner { public static void main(String args[]) { // Inside a method(main) only, Anonymous class is declared Person p=new Person() //Statement do not end with semicolon(as we cant create object for abstract class or interface) { void eat(){System.out.println("nice fruits");} Anonymous Inner Class (only body is there without identity) }; p.eat(); } }
  • 22. • Generation of class Files: • Person.class • Person $ 1.class (For Anonymous class, as they don’t have any name, automatically no's will be assigned)
  • 23. • Internal working of given code Person p=new Person() { void eat(){System.out.println("nice fruits");} }; • A class is created but its name is decided by the compiler which extends the Person class and provides the implementation of the eat() method. • An object of Anonymous class is created that is referred by p reference variable of Person type.
  • 24. interface Eatable { void eat(); } class TestAnnonymousInner1 { public static void main(String args[]) { Eatable e=new Eatable() //No Semicolon { public void eat(){System.out.println("nice fruits");} }; e.eat(); } }
  • 25. Note: When we compile a nested class, two different class files will be created with names Outerclass.class Outerclass$Nestedclass.class • Local Class is named as Outerclass$1Localclass.class • Anonymous class is named as Outerclass$1.class