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
Ad

More Related Content

What's hot (20)

C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
Grishma Rajput
 
Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2
MOHIT TOMAR
 
Member Function in C++
Member Function in C++ Member Function in C++
Member Function in C++
NikitaKaur10
 
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiConstants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya Jyothi
SowmyaJyothi3
 
Function in C
Function in CFunction in C
Function in C
Dr. Abhineet Anand
 
Storage class
Storage classStorage class
Storage class
Joy Forerver
 
Function in c
Function in cFunction in c
Function in c
savitamhaske
 
Friend function in c++
Friend function in c++ Friend function in c++
Friend function in c++
University of Madras
 
Switch case in C++
Switch case in C++Switch case in C++
Switch case in C++
Barani Govindarajan
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
programming9
 
Function
FunctionFunction
Function
jayesh30sikchi
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variables
sangrampatil81
 
Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c language
kiran Patel
 
functions in C and types
functions in C and typesfunctions in C and types
functions in C and types
mubashir farooq
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
Harsh Patel
 
Inheritance in c++theory
Inheritance in c++theoryInheritance in c++theory
Inheritance in c++theory
ProfSonaliGholveDoif
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
C functions
C functionsC functions
C functions
University of Potsdam
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
Dhrumil Patel
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
Grishma Rajput
 
Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2
MOHIT TOMAR
 
Member Function in C++
Member Function in C++ Member Function in C++
Member Function in C++
NikitaKaur10
 
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiConstants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya Jyothi
SowmyaJyothi3
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
programming9
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variables
sangrampatil81
 
Dynamic memory Allocation in c language
Dynamic memory Allocation in c languageDynamic memory Allocation in c language
Dynamic memory Allocation in c language
kiran Patel
 
functions in C and types
functions in C and typesfunctions in C and types
functions in C and types
mubashir farooq
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
Harsh Patel
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
Dhrumil Patel
 

Similar to Nested class (20)

Nested classes in java
Nested classes in javaNested classes in java
Nested classes in java
Richa Singh
 
Java Nested class Concept
Java Nested class ConceptJava Nested class Concept
Java Nested class Concept
jagriti srivastava
 
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
RithwikRanjan
 
Inner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in javaInner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in java
Adil Mehmoood
 
Nested class in java
Nested class in javaNested class in java
Nested class in java
ChiradipBhattacharya
 
L5 classes, objects, nested and inner class
L5 classes, objects, nested and inner classL5 classes, objects, nested and inner class
L5 classes, objects, nested and inner class
teach4uin
 
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
 
Nested classes in java
Nested classes in javaNested classes in java
Nested classes in java
ChiradipBhattacharya
 
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
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
DevaKumari Vijay
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
Epsiba1
 
Inner class
Inner classInner class
Inner class
Guna Sekaran
 
Javasession8
Javasession8Javasession8
Javasession8
Rajeev Kumar
 
Inner Classes in Java
Inner Classes in JavaInner Classes in Java
Inner Classes in Java
Dallington Asingwire
 
WINSEMFRE2024-25_CSE2005_ETH_AP2024255000715_2025-03-18_Reference-Material-I....
WINSEMFRE2024-25_CSE2005_ETH_AP2024255000715_2025-03-18_Reference-Material-I....WINSEMFRE2024-25_CSE2005_ETH_AP2024255000715_2025-03-18_Reference-Material-I....
WINSEMFRE2024-25_CSE2005_ETH_AP2024255000715_2025-03-18_Reference-Material-I....
belgiumsckgr
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
Abdii Rashid
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
DeeptiJava
 
Core java oop
Core java oopCore java oop
Core java oop
Parth Shah
 
unit 2 java.pptx
unit 2 java.pptxunit 2 java.pptx
unit 2 java.pptx
AshokKumar587867
 
Java- Nested Classes
Java- Nested ClassesJava- Nested Classes
Java- Nested Classes
Prabhdeep Singh
 
Nested classes in java
Nested classes in javaNested classes in java
Nested classes in java
Richa Singh
 
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
RithwikRanjan
 
Inner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in javaInner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in java
Adil Mehmoood
 
L5 classes, objects, nested and inner class
L5 classes, objects, nested and inner classL5 classes, objects, nested and inner class
L5 classes, objects, nested and inner class
teach4uin
 
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
 
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
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
Epsiba1
 
WINSEMFRE2024-25_CSE2005_ETH_AP2024255000715_2025-03-18_Reference-Material-I....
WINSEMFRE2024-25_CSE2005_ETH_AP2024255000715_2025-03-18_Reference-Material-I....WINSEMFRE2024-25_CSE2005_ETH_AP2024255000715_2025-03-18_Reference-Material-I....
WINSEMFRE2024-25_CSE2005_ETH_AP2024255000715_2025-03-18_Reference-Material-I....
belgiumsckgr
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
DeeptiJava
 
Ad

More from Daman Toor (15)

Lab exam 5_5_15
Lab exam 5_5_15Lab exam 5_5_15
Lab exam 5_5_15
Daman Toor
 
Lab exam setb_5_5_2015
Lab exam setb_5_5_2015Lab exam setb_5_5_2015
Lab exam setb_5_5_2015
Daman Toor
 
String slide
String slideString slide
String slide
Daman Toor
 
Uta005
Uta005Uta005
Uta005
Daman Toor
 
Inheritance1
Inheritance1Inheritance1
Inheritance1
Daman Toor
 
Inheritance
InheritanceInheritance
Inheritance
Daman Toor
 
Lab exp (creating classes and objects)
Lab exp (creating classes and objects)Lab exp (creating classes and objects)
Lab exp (creating classes and objects)
Daman Toor
 
Practice
PracticePractice
Practice
Daman Toor
 
Parking ticket simulator program
Parking ticket simulator programParking ticket simulator program
Parking ticket simulator program
Daman Toor
 
Lab exp (declaring classes)
Lab exp (declaring classes)Lab exp (declaring classes)
Lab exp (declaring classes)
Daman Toor
 
Lab exp declaring arrays)
Lab exp declaring arrays)Lab exp declaring arrays)
Lab exp declaring arrays)
Daman Toor
 
Java assignment 1
Java assignment 1Java assignment 1
Java assignment 1
Daman Toor
 
Operators
OperatorsOperators
Operators
Daman Toor
 
Identifiers, keywords and types
Identifiers, keywords and typesIdentifiers, keywords and types
Identifiers, keywords and types
Daman Toor
 
Classes & object
Classes & objectClasses & object
Classes & object
Daman Toor
 
Lab exam 5_5_15
Lab exam 5_5_15Lab exam 5_5_15
Lab exam 5_5_15
Daman Toor
 
Lab exam setb_5_5_2015
Lab exam setb_5_5_2015Lab exam setb_5_5_2015
Lab exam setb_5_5_2015
Daman Toor
 
Lab exp (creating classes and objects)
Lab exp (creating classes and objects)Lab exp (creating classes and objects)
Lab exp (creating classes and objects)
Daman Toor
 
Parking ticket simulator program
Parking ticket simulator programParking ticket simulator program
Parking ticket simulator program
Daman Toor
 
Lab exp (declaring classes)
Lab exp (declaring classes)Lab exp (declaring classes)
Lab exp (declaring classes)
Daman Toor
 
Lab exp declaring arrays)
Lab exp declaring arrays)Lab exp declaring arrays)
Lab exp declaring arrays)
Daman Toor
 
Java assignment 1
Java assignment 1Java assignment 1
Java assignment 1
Daman Toor
 
Identifiers, keywords and types
Identifiers, keywords and typesIdentifiers, keywords and types
Identifiers, keywords and types
Daman Toor
 
Classes & object
Classes & objectClasses & object
Classes & object
Daman Toor
 
Ad

Recently uploaded (20)

Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 

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);