SlideShare a Scribd company logo
Nested Class
Example
class OuterClass { ... class NestedClass { ... } }
• Nested classes are divided into two categories:
static and 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.
Why Use Nested Classes?
• Compelling reasons for using nested classes include the following:
• 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.
Static Nested Classes
• As with class methods and variables, a static nested class is
associated with its outer class.
• 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.
• 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();
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.
Example
• 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, you must first instantiate the outer class.
Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
• There are two special kinds of inner classes: local classes and anonymous
classes.
Local Classes
• Declaring Local Classes
public class LocalClassExample {
static String regularExpression = "[^0-9]";
public static void validatePhoneNumber(
String phoneNumber1, String phoneNumber2) {
final int numberLength = 10;
class PhoneNumber {
String formattedPhoneNumber = null;
PhoneNumber(String phoneNumber){
String currentNumber = phoneNumber.replaceAll(
regularExpression, "");
if (currentNumber.length() == numberLength)
formattedPhoneNumber = currentNumber;
else
formattedPhoneNumber = null;
}
public String getNumber() {
return formattedPhoneNumber;
}
PhoneNumber myNumber1 = new PhoneNumber(phoneNumber1);
PhoneNumber myNumber2 = new PhoneNumber(phoneNumber2);
if (myNumber1.getNumber() == null)
System.out.println("First number is invalid");
else
System.out.println("First number is " + myNumber1.getNumber());
if (myNumber2.getNumber() == null)
System.out.println("Second number is invalid");
else
System.out.println("Second number is " + myNumber2.getNumber());
}
public static void main(String... args) {
validatePhoneNumber("123-456-7890", "456-7890");
}
} Output:
First number is 1234567890
Second number is invalid
Anonymous Classes
• 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.
Shadowing
• If a declaration of a type (such as a member
variable or a parameter name) in a particular
scope (such as an inner class or a method
definition) has the same name as another
declaration in the enclosing scope, then the
declaration shadows the declaration of the
enclosing scope.
• You cannot refer to a shadowed declaration by
its name alone.
public class ShadowTest {
public int x = 0;
class FirstLevel {
public int x = 1;
void methodInFirstLevel(int x) {
System.out.println("x = " + x);
System.out.println("this.x = " + this.x);
System.out.println("ShadowTest.this.x = " +
ShadowTest.this.x);
}
}
public static void main(String... args) {
ShadowTest st = new ShadowTest();
ShadowTest.FirstLevel fl = st.new FirstLevel();
fl.methodInFirstLevel(23);
}
}
Output
x = 23
this.x = 1
ShadowTest.this.x = 0
• This example defines three variables named x:
– the member variable of the class ShadowTest,
– the member variable of the inner class FirstLevel,
– and the parameter in the method methodInFirstLevel.
• The variable x defined as a parameter of the method
methodInFirstLevel shadows the variable of the inner class
FirstLevel.
• Consequently, when you use the variable x in the method
methodInFirstLevel, it refers to the method parameter.
• To refer to the member variable of the inner class FirstLevel, use the
keyword this to represent the enclosing scope:
System.out.println("this.x = " + this.x);
• Refer to member variables that enclose larger scopes by the class
name to which they belong.
• For example, the following statement accesses the member
variable of the class ShadowTest from the method
methodInFirstLevel:
System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
Nested class
Nested class
Nested class
Nested class
Nested class
Nested class
Nested class
Nested class
Nested class
Nested class
Nested class
Nested class

More Related Content

PPTX
classes and objects in C++
PPTX
Object oriented programming in python
PPTX
Constructor and Types of Constructors
PPTX
Function C programming
PPTX
Inline function
PPTX
Inheritance in C++
PPTX
inheritance c++
classes and objects in C++
Object oriented programming in python
Constructor and Types of Constructors
Function C programming
Inline function
Inheritance in C++
inheritance c++

What's hot (20)

PPTX
Abstract class in c++
PPTX
[OOP - Lec 19] Static Member Functions
PPTX
Python OOPs
PPTX
592047465-4-Const-vs-Non-const-Functions-Amd-Static-Data-Members-Functions.pptx
PPTX
Inheritance
PPTX
Object Oriented Programming with C#
PPTX
Destructors
PDF
Function overloading ppt
PPTX
PDF
Array data structure
PDF
4 pillars of OOPS CONCEPT
PPTX
Object oriented programming with python
PPTX
Arrays In C++
PPTX
Constructor in java
PDF
Constructors and destructors
PPTX
Unary operator overloading
PDF
Object oriented approach in python programming
PPT
inhertance c++
Abstract class in c++
[OOP - Lec 19] Static Member Functions
Python OOPs
592047465-4-Const-vs-Non-const-Functions-Amd-Static-Data-Members-Functions.pptx
Inheritance
Object Oriented Programming with C#
Destructors
Function overloading ppt
Array data structure
4 pillars of OOPS CONCEPT
Object oriented programming with python
Arrays In C++
Constructor in java
Constructors and destructors
Unary operator overloading
Object oriented approach in python programming
inhertance c++
Ad

Similar to Nested class (20)

DOCX
Nested classes in java
PPTX
Java Nested class Concept
PPT
A1771937735_21789_14_2018__16_ Nested Classes.ppt
PPT
Inner classes ,annoumous and outer classes in java
DOCX
Nested class in java
PPT
L5 classes, objects, nested and inner class
PPTX
Inner Classes & Multi Threading in JAVA
PPTX
Nested classes in java
PPTX
Java Nested classes, static class and methods, nested blocks_Inner_Classes.pptx
PPTX
Java Programming inner and Nested classes.pptx
PPTX
Unit3 part1-class
PPTX
class as the basis.pptx
PPTX
Inner class
PPTX
Javasession8
PDF
Inner Classes in Java
PPTX
WINSEMFRE2024-25_CSE2005_ETH_AP2024255000715_2025-03-18_Reference-Material-I....
PPTX
Java chapter 5
PPTX
Java Inner Class
PPTX
Core java oop
PPTX
unit 2 java.pptx
Nested classes in java
Java Nested class Concept
A1771937735_21789_14_2018__16_ Nested Classes.ppt
Inner classes ,annoumous and outer classes in java
Nested class in java
L5 classes, objects, nested and inner class
Inner Classes & Multi Threading in JAVA
Nested classes in java
Java Nested classes, static class and methods, nested blocks_Inner_Classes.pptx
Java Programming inner and Nested classes.pptx
Unit3 part1-class
class as the basis.pptx
Inner class
Javasession8
Inner Classes in Java
WINSEMFRE2024-25_CSE2005_ETH_AP2024255000715_2025-03-18_Reference-Material-I....
Java chapter 5
Java Inner Class
Core java oop
unit 2 java.pptx
Ad

More from Daman Toor (15)

DOCX
Lab exam 5_5_15
DOCX
Lab exam setb_5_5_2015
PPT
String slide
DOCX
Uta005
PPTX
Inheritance1
PPTX
Inheritance
DOC
Lab exp (creating classes and objects)
DOCX
Practice
DOCX
Parking ticket simulator program
DOC
Lab exp (declaring classes)
DOC
Lab exp declaring arrays)
DOCX
Java assignment 1
PPT
Operators
PPTX
Identifiers, keywords and types
PPTX
Classes & object
Lab exam 5_5_15
Lab exam setb_5_5_2015
String slide
Uta005
Inheritance1
Inheritance
Lab exp (creating classes and objects)
Practice
Parking ticket simulator program
Lab exp (declaring classes)
Lab exp declaring arrays)
Java assignment 1
Operators
Identifiers, keywords and types
Classes & object

Recently uploaded (20)

PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Cell Structure & Organelles in detailed.
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Business Ethics Teaching Materials for college
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
01-Introduction-to-Information-Management.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
master seminar digital applications in india
PDF
RMMM.pdf make it easy to upload and study
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Institutional Correction lecture only . . .
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Renaissance Architecture: A Journey from Faith to Humanism
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
2.FourierTransform-ShortQuestionswithAnswers.pdf
O7-L3 Supply Chain Operations - ICLT Program
Cell Structure & Organelles in detailed.
VCE English Exam - Section C Student Revision Booklet
Business Ethics Teaching Materials for college
Microbial diseases, their pathogenesis and prophylaxis
01-Introduction-to-Information-Management.pdf
Basic Mud Logging Guide for educational purpose
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPH.pptx obstetrics and gynecology in nursing
master seminar digital applications in india
RMMM.pdf make it easy to upload and study
STATICS OF THE RIGID BODIES Hibbelers.pdf
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Institutional Correction lecture only . . .
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
TR - Agricultural Crops Production NC III.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf

Nested class

  • 2. Example class OuterClass { ... class NestedClass { ... } } • Nested classes are divided into two categories: static and non-static. • Nested classes that are declared static are called static nested classes. • Non-static nested classes are called inner classes.
  • 3. 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.
  • 4. Why Use Nested Classes? • Compelling reasons for using nested classes include the following: • 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.
  • 5. Static Nested Classes • As with class methods and variables, a static nested class is associated with its outer class. • 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. • 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();
  • 6. 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.
  • 7. Example • 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, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass.InnerClass innerObject = outerObject.new InnerClass(); • There are two special kinds of inner classes: local classes and anonymous classes.
  • 8. Local Classes • Declaring Local Classes public class LocalClassExample { static String regularExpression = "[^0-9]"; public static void validatePhoneNumber( String phoneNumber1, String phoneNumber2) { final int numberLength = 10; class PhoneNumber { String formattedPhoneNumber = null; PhoneNumber(String phoneNumber){ String currentNumber = phoneNumber.replaceAll( regularExpression, ""); if (currentNumber.length() == numberLength) formattedPhoneNumber = currentNumber; else formattedPhoneNumber = null; }
  • 9. public String getNumber() { return formattedPhoneNumber; } PhoneNumber myNumber1 = new PhoneNumber(phoneNumber1); PhoneNumber myNumber2 = new PhoneNumber(phoneNumber2); if (myNumber1.getNumber() == null) System.out.println("First number is invalid"); else System.out.println("First number is " + myNumber1.getNumber()); if (myNumber2.getNumber() == null) System.out.println("Second number is invalid"); else System.out.println("Second number is " + myNumber2.getNumber()); } public static void main(String... args) { validatePhoneNumber("123-456-7890", "456-7890"); } } Output: First number is 1234567890 Second number is invalid
  • 10. Anonymous Classes • 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.
  • 11. Shadowing • If a declaration of a type (such as a member variable or a parameter name) in a particular scope (such as an inner class or a method definition) has the same name as another declaration in the enclosing scope, then the declaration shadows the declaration of the enclosing scope. • You cannot refer to a shadowed declaration by its name alone.
  • 12. public class ShadowTest { public int x = 0; class FirstLevel { public int x = 1; void methodInFirstLevel(int x) { System.out.println("x = " + x); System.out.println("this.x = " + this.x); System.out.println("ShadowTest.this.x = " + ShadowTest.this.x); } } public static void main(String... args) { ShadowTest st = new ShadowTest(); ShadowTest.FirstLevel fl = st.new FirstLevel(); fl.methodInFirstLevel(23); } } Output x = 23 this.x = 1 ShadowTest.this.x = 0
  • 13. • This example defines three variables named x: – the member variable of the class ShadowTest, – the member variable of the inner class FirstLevel, – and the parameter in the method methodInFirstLevel. • The variable x defined as a parameter of the method methodInFirstLevel shadows the variable of the inner class FirstLevel. • Consequently, when you use the variable x in the method methodInFirstLevel, it refers to the method parameter. • To refer to the member variable of the inner class FirstLevel, use the keyword this to represent the enclosing scope: System.out.println("this.x = " + this.x); • Refer to member variables that enclose larger scopes by the class name to which they belong. • For example, the following statement accesses the member variable of the class ShadowTest from the method methodInFirstLevel: System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);