SlideShare a Scribd company logo
1 of 12
NESTED CLASS IN JAVA
Bachelor of Technology
Computer Science and Engineering
Submitted By
CHIRADIP BHATTACHARYA (13000216109)
NOVEMBER 2018
Techno India
EM-4/1, Sector-V, Salt Lake
Kolkata- 700091
West Bengal
India
TABLE OF CONTENTS
1. Abstract
2. Introduction
3. Body
i) Nested Classes
ii) Types of Nested Classes
iii) Non-static Nested Classes
(a) Instance Inner Classes
(b) Method Local Classes
(c) Anonymous Inner Classes
iv) Static Nested Classes
v) Differences between Static and Non-static Nested Classes
vi) Advantages of Nested Classes
vii) Disadvantages of Nested Classes
4. Conclusion
5. References
1. Abstract
JAVA is an Object Oriented Programming (OOP) language with encapsulation as the
basis of everything in it. Everything in java is wrapped up into a single unit called Class,
which can also be nested or have a Class structure within a Class. Just like a nested if-else
structure present in JAVA, we can also incorporate a similar structure to Classes creating
Nested Classes. In this paper, we delve deeper into the concepts behind these Nested
Classes, their usage and utility and their advantages. This paper would also be focusing
on the differences among the types of Nested class and also discuss about their various
types.
2. Introduction
JAVA being a modern Object Oriented Programming (OOP) language has many features
like – a) Abstraction, b) Encapsulation, c) Inheritance, and d) Polymorphism as its core
facets. One of JAVA’s prime feature is encapsulation, wherein, all data members and
objects are wrapped up into a single unit called a Class. Objects in JAVA embody the
state (as data variables) and behavior (as methods) of real-world entities, following a
general template as defined, which is the Class. A Class having another Class within it
forms what is known as a Nested Class. A Nested Class can be overviewed as a structure
which can be used to model the complexities of the real world, where an entity many be
falling under many sub-classes, but those sub-classes are only logical to the class
immediately preceding them.
The Top level or Outer classes, are declared inside a package and are visible throughout
the package or perhaps even further depending upon the access specifier used to specify
the Outer Class. Normally, although not always, the Outer class maybe declared in their
own file, while it is mandatory for Outer classes declared public, must be defined in their
own file.
The Nested and inner classes, are declared inside an Outer class (or even a method block)
and can be visible only to outer class, or may have a wider visibility as per the scope of
the inner class set the access specifier. Besides, out own thought process of grouping
things which are alike in nature, together, helps us to conceive of Nested classes far more
easily. The main features of ease of organization and access, without having to type in
redundant code, helps Nested classes to stand out and be approached by more and more
programmers.
3. Body
i) Nested Classes
The class written within a class is called the Nested class, and the class that holds the
inner class is called the Outer class. Syntax for writing a Nested class can be illustrated
as follows –
class OuterClass {
(…..code…..)
class NestedClass {
(…..code…..)
}
}
ii) Types of Nested Classes
There are typically two types of Nested Classes –
a) Non-static nested classes :
These are the non-static classes also known as Inner classes, which are not
declared with the static keyword. They can be further divided into –
1. Instance Inner classes
2. Method Local Inner classes
3. Anonymous Inner classes
b) Static nested classes :
These are the static classes declared with the static keyword, which is the modifier
of that class. Static classes mostly behave like regular classes, only that their
mode of accessing the static variables and methods are different.
Fig. 1 Types of Nested Classes
iii) Non-static Nested Classes
It is the non-static nested class defined in the scope of another class or interface.
These classes can directly access all variables and methods of enclosing class
(including private fields and methods) and is associated with an instance of its
enclosing class.
There are typically three types of Non-static Nested Classes –
a) Instance Inner classes :
These are the non-static classes also known as Inner classes, which are not
declared with the static keyword. It is the most basic type of non-static nested
class. It is created when a class is written inside another class and the inner class
can be used to access the private members of the outer class. To instantiate the
inner class, the outer class has to be instantiated first. Then, using the object of the
outer class, the inner class can be instantiated and its methods can be called. The
Syntax can be defined as follows –
class Outer_class{
(code …)
class Inner_class{
(code …)
}
}
Sample Code –
Explanation –
The class ‘Outer_Demo’ is the outer class enclosing the inner class ‘Inner_Demo’
and the method ‘display_Inner()’. A member variable of the outer class ‘num’ of
type integer is declared. Then, the inner class is declared as private and within it a
simple ‘print()’ method is declared which just prints “This is the inner class”.
Then, the ‘display_Inner()’ method is declared in the scope of the outer class.
Then, a new driver class ‘My_class’ is created to run the code. The ‘main()’
method of this class first instantiates the outer class and then the object of the
outer class is used to call the inner class method. Here, the inner class can also
access ‘num’ and also the private variables of the outer class, if any were present
within it.
Accessing the private members of an Inner class –
Sample Code –
Explanation –
This is the almost the same as the other Sample code above, but this one has a
private variable of integer type ‘num’ which is accessed by the inner class. The
inner class has another method ‘getNum()’ which returns the value of the ‘num’
variable as it receives it. The Driver class ‘My_class’ instantiates the outer class’s
reference in the ‘main()’ method with the syntax –
Outer_class_name object1 = new Outer_class_name();
And then instantiates the inner class’s reference as per the syntax –
Outer_class_name. Inner_class_name object2 = object1.new
Inner_class_name();
Then the object reference of the inner class created ‘inner’ is used to access the
method ‘getNum()’ of the inner class as per the syntax –
object.Method_name
And upon compilation and execution the code yields,
Which shows that the inner class method is executed and the value of ‘num’ as
given to the outer class is preserved as the same variable is accessed by the
instance of the inner class.
b) Method Local Inner classes :
It is the type of non-static nested class that is defined in a block, typically in a
method which is again, inside the outer class. Local inner class cannot be invoked
from outside the method in which the inner class is declared, as it would go
beyond the scope of the inner class. It can only access only the ‘final’ parameters
of the enclosing block, as it captures that variable or parameter, whereas, the local
inner class can access the members of the enclosing class. The inner class cannot
have any static data members (unless they are declared final) and static methods.
The Syntax for such classes are as follows –
class Outer_class{
return_type function_name(parameters(if any)){
class Inner_class{
}
}
}
Sample Code –
Explanation –
The outer class ‘Outer_Demo’ encloses the method ‘hello(parameter)’ which is a
parameterized function with a ‘final’ ‘int’ variable ‘param’, and the inner class
‘Inner_Demo’. The inner class further has a ‘void’ ‘inner’ method which prints
the value of the ‘param’ variable as obtained by the inner class. Upon compilation
and execution , the following code prints the value of ‘param’ as accepted by the
‘hello()’ function.
A Variation of the above code can be as follows –
Sample Code –
Explanation –
The outer class ‘Outer_Demo’ encloses the method ‘main()’ which is the main
function of the outer class. The inner class ‘Inner_Demo’ is declared inside the
main method and a ‘static’ ‘final’ ‘param’ variable is initialized. Then another
function ‘inner()’ is declared which prints the value of the ‘param’ variable. Upon
compilation and execution, the following code prints the value of ‘param’ as
initialized within the inner class. If the variable is declared without being static
then there would be a compilation error.
c) Anonymous Inner classes :
Local classes with no name are called Anonymous classes. It helps to make code
more concise by allowing us to declare and instantiate a class at the same time. It
is used when a local class is to be used only once in the code. It is often used to
override method of a class or interface. They are much like expressions rather
than a class declaration and they have the same access to local variables of the
enclosing scope as local classes. Anonymous classes can have static members
provided only if they are ‘final’ variables. Its Syntax is as follows –
public class SuperClass {
public void doIt() {
System.out.println("SuperClass doIt()");
}
}
(Inside a driver class within a main function)
SuperClass instance = new SuperClass() {
public void doIt() {
System.out.println("Anonymous class doIt()");
}
};
instance.doIt();
Explanation –
Compiling and executing this code would result in “Anonymous class doIt()”
being printed to System.out. The anonymous class subclasses (extends)
SuperClass and overrides the doIt() method.
Sample Code –
Explanation –
The above code is for the inner anonymous class to perform EventHandling. Here,
‘Button’ is the outer class and the anonymous class is created when the instance of
the Button class, ‘btn’ calls the ‘setOnAction()’ method, to perform the Event
Handling.
iv) Static Nested Classes
A static nested class is a nested class which is a static member of the outer class. It
can be accessed without instantiating the outer class, using other static members. Just
like static members, a static nested class does not have access to the instance variables
and methods of the outer class. The Syntax of a Static Nested Class is –
class Outer_class{
static class Inner_class{
}
}
Sample Code –
Explanation –
The outer class ‘Outer_Demo’ encloses the static nested class ‘Nested_Demo’, which
in turn has a function ‘my_method’ which is simply placed to print a line. Then, the
main method is used to instantiate the nested static class. The Syntax for doing so is –
Outer_class.Nested_class object = new Outer_class.Nested_class();
Then the object is used to access the enclosed function which is non-static. Had it
been static a direct metod name would invoke the function.
On compiling and executing the code, the result is –
v) Difference between Static and Non-static Nested Classes
a) Nested static class doesn't need reference of Outer class, but non-static nested class
or Inner class requires the Outer class reference. One cannot create instance of
Inner class without creating instance of Outer class. This is by far most important
thing to consider while making a nested class static or non static. Syntactically,
Outer_class.Inner_class method_name = new Outer_Class.Inner_Class(); for static
inner class object creation, and Outer_class.Inner_class method_name = new
Outer_Class.new Inner_Class(); for non-static inner class object creation.
b) Static class is actually static member of class and can be used in static context e.g.
static method or static block of Outer class.
c) Another difference between static and non static nested class is that one cannot
access non static members e.g. method and field into nested static class directly. If
it is done an error like "non static member cannot be used in static context" is
displayed. While Inner class can access both static and non static member of Outer
class.
vi) Advantages of Nested Classes
a) It is a way of logically grouping classes that are only used in one place.
b) Can access all the members of the outer class including private data members and
methods.
c) Can be declared private, public, protected or package private, unlike regular
classes that can be only declared public or package private.
d) It increases encapsulation as it can itself be declared private and still access the
outer class’ private members.
e) It can lead to more readable and maintainable code as it places the code closer to
where it is used.
vii) Disadvantages of Nested Classes
a) Anonymous classes may make code difficult to read and understand.
b) Classes contain a mixture of purposes, and thereby, no longer remain specific
and easily understandable.
c) Inner classes may even cause security concerns.
4. Conclusion
JAVA being an Object Oriented Programming (OOP) Language offers us the priced
facet of encapsulation. This encapsulation can also be extended to as far as the classes
themselves which can also be encapsulated into yet other enclosing classes. Thus, the
concept of Nested classes. Besides, all the advantages of Nested classes as stated above,
they also help us to produce more concise and logically grouped code, which are far
more readable and easy to understand. Nested classes especially anonymous classes are
especially useful as their references are only created when required, thereby, leading to
the more effective usage of memory as a resource. Thus, Nested classes are a valuable
asset to JAVA programming language, which caters to the unique style of programming
of each programmer and thereby, provides the programmer with a lot of tools to foster
their unique style and making programming a more enjoyable experience. But as with all
great powers, comes great responsibilities, Nested classes should be used wisely as, they
can sometimes, make the code difficult to read and understand, and in some situations,
inner classes may even cause security concerns.
5. References
i) THE COMPLETE REFERENCE TO JAVA by Herbert Schildt, TATA McGRAW
HILL publication
ii) https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
iii) http://www.java67.com/2012/10/nested-class-java-static-vs-non-static-inner.html
iv)https://dzone.com/articles/nested-classes-in-java
v) https://www.javatpoint.com/java-inner-class
vi)https://www.geeksforgeeks.org/nested-classes-java/

More Related Content

What's hot (20)

Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Inheritance
InheritanceInheritance
Inheritance
 
Constructors in java
Constructors in javaConstructors in java
Constructors in java
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Java- Nested Classes
Java- Nested ClassesJava- Nested Classes
Java- Nested Classes
 
Java program structure
Java program structure Java program structure
Java program structure
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in java
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Abstraction java
Abstraction javaAbstraction java
Abstraction java
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Inner Classes in Java
Inner Classes in JavaInner Classes in Java
Inner Classes in Java
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
interface in c#
interface in c#interface in c#
interface in c#
 

Similar to NESTED CLASSES IN JAVA EXPLAINED

Nested classes in java
Nested classes in javaNested classes in java
Nested classes in javaRicha Singh
 
Object oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxObject oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxDaveEstonilo
 
Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVATech_MX
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 eehomeworkping9
 
A1771937735_21789_14_2018__16_ Nested Classes.ppt
A1771937735_21789_14_2018__16_ Nested Classes.pptA1771937735_21789_14_2018__16_ Nested Classes.ppt
A1771937735_21789_14_2018__16_ Nested Classes.pptRithwikRanjan
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core ParcticalGaurav Mehta
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview QestionsArun Vasanth
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
types of classes in java
types of classes in javatypes of classes in java
types of classes in javaNouman Riaz
 

Similar to NESTED CLASSES IN JAVA EXPLAINED (20)

Nested classes in java
Nested classes in javaNested classes in java
Nested 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
 
Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVA
 
Inner class
Inner classInner class
Inner class
 
Inner class
Inner classInner class
Inner class
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 ee
 
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
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
 
4 Classes & Objects
4 Classes & Objects4 Classes & Objects
4 Classes & Objects
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
 
Lecture 10
Lecture 10Lecture 10
Lecture 10
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
java tutorial 4
 java tutorial 4 java tutorial 4
java tutorial 4
 
Java basics
Java basicsJava basics
Java basics
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
 
types of classes in java
types of classes in javatypes of classes in java
types of classes in java
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 

Recently uploaded

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 

Recently uploaded (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 

NESTED CLASSES IN JAVA EXPLAINED

  • 1. NESTED CLASS IN JAVA Bachelor of Technology Computer Science and Engineering Submitted By CHIRADIP BHATTACHARYA (13000216109) NOVEMBER 2018 Techno India EM-4/1, Sector-V, Salt Lake Kolkata- 700091 West Bengal India
  • 2. TABLE OF CONTENTS 1. Abstract 2. Introduction 3. Body i) Nested Classes ii) Types of Nested Classes iii) Non-static Nested Classes (a) Instance Inner Classes (b) Method Local Classes (c) Anonymous Inner Classes iv) Static Nested Classes v) Differences between Static and Non-static Nested Classes vi) Advantages of Nested Classes vii) Disadvantages of Nested Classes 4. Conclusion 5. References
  • 3. 1. Abstract JAVA is an Object Oriented Programming (OOP) language with encapsulation as the basis of everything in it. Everything in java is wrapped up into a single unit called Class, which can also be nested or have a Class structure within a Class. Just like a nested if-else structure present in JAVA, we can also incorporate a similar structure to Classes creating Nested Classes. In this paper, we delve deeper into the concepts behind these Nested Classes, their usage and utility and their advantages. This paper would also be focusing on the differences among the types of Nested class and also discuss about their various types. 2. Introduction JAVA being a modern Object Oriented Programming (OOP) language has many features like – a) Abstraction, b) Encapsulation, c) Inheritance, and d) Polymorphism as its core facets. One of JAVA’s prime feature is encapsulation, wherein, all data members and objects are wrapped up into a single unit called a Class. Objects in JAVA embody the state (as data variables) and behavior (as methods) of real-world entities, following a general template as defined, which is the Class. A Class having another Class within it forms what is known as a Nested Class. A Nested Class can be overviewed as a structure which can be used to model the complexities of the real world, where an entity many be falling under many sub-classes, but those sub-classes are only logical to the class immediately preceding them. The Top level or Outer classes, are declared inside a package and are visible throughout the package or perhaps even further depending upon the access specifier used to specify the Outer Class. Normally, although not always, the Outer class maybe declared in their own file, while it is mandatory for Outer classes declared public, must be defined in their own file. The Nested and inner classes, are declared inside an Outer class (or even a method block) and can be visible only to outer class, or may have a wider visibility as per the scope of the inner class set the access specifier. Besides, out own thought process of grouping things which are alike in nature, together, helps us to conceive of Nested classes far more easily. The main features of ease of organization and access, without having to type in redundant code, helps Nested classes to stand out and be approached by more and more programmers.
  • 4. 3. Body i) Nested Classes The class written within a class is called the Nested class, and the class that holds the inner class is called the Outer class. Syntax for writing a Nested class can be illustrated as follows – class OuterClass { (…..code…..) class NestedClass { (…..code…..) } } ii) Types of Nested Classes There are typically two types of Nested Classes – a) Non-static nested classes : These are the non-static classes also known as Inner classes, which are not declared with the static keyword. They can be further divided into – 1. Instance Inner classes 2. Method Local Inner classes 3. Anonymous Inner classes b) Static nested classes : These are the static classes declared with the static keyword, which is the modifier of that class. Static classes mostly behave like regular classes, only that their mode of accessing the static variables and methods are different.
  • 5. Fig. 1 Types of Nested Classes iii) Non-static Nested Classes It is the non-static nested class defined in the scope of another class or interface. These classes can directly access all variables and methods of enclosing class (including private fields and methods) and is associated with an instance of its enclosing class. There are typically three types of Non-static Nested Classes – a) Instance Inner classes : These are the non-static classes also known as Inner classes, which are not declared with the static keyword. It is the most basic type of non-static nested class. It is created when a class is written inside another class and the inner class can be used to access the private members of the outer class. To instantiate the inner class, the outer class has to be instantiated first. Then, using the object of the outer class, the inner class can be instantiated and its methods can be called. The Syntax can be defined as follows – class Outer_class{ (code …) class Inner_class{ (code …) } }
  • 6. Sample Code – Explanation – The class ‘Outer_Demo’ is the outer class enclosing the inner class ‘Inner_Demo’ and the method ‘display_Inner()’. A member variable of the outer class ‘num’ of type integer is declared. Then, the inner class is declared as private and within it a simple ‘print()’ method is declared which just prints “This is the inner class”. Then, the ‘display_Inner()’ method is declared in the scope of the outer class. Then, a new driver class ‘My_class’ is created to run the code. The ‘main()’ method of this class first instantiates the outer class and then the object of the outer class is used to call the inner class method. Here, the inner class can also access ‘num’ and also the private variables of the outer class, if any were present within it. Accessing the private members of an Inner class –
  • 7. Sample Code – Explanation – This is the almost the same as the other Sample code above, but this one has a private variable of integer type ‘num’ which is accessed by the inner class. The inner class has another method ‘getNum()’ which returns the value of the ‘num’ variable as it receives it. The Driver class ‘My_class’ instantiates the outer class’s reference in the ‘main()’ method with the syntax – Outer_class_name object1 = new Outer_class_name(); And then instantiates the inner class’s reference as per the syntax – Outer_class_name. Inner_class_name object2 = object1.new Inner_class_name(); Then the object reference of the inner class created ‘inner’ is used to access the method ‘getNum()’ of the inner class as per the syntax – object.Method_name And upon compilation and execution the code yields, Which shows that the inner class method is executed and the value of ‘num’ as given to the outer class is preserved as the same variable is accessed by the instance of the inner class. b) Method Local Inner classes : It is the type of non-static nested class that is defined in a block, typically in a method which is again, inside the outer class. Local inner class cannot be invoked
  • 8. from outside the method in which the inner class is declared, as it would go beyond the scope of the inner class. It can only access only the ‘final’ parameters of the enclosing block, as it captures that variable or parameter, whereas, the local inner class can access the members of the enclosing class. The inner class cannot have any static data members (unless they are declared final) and static methods. The Syntax for such classes are as follows – class Outer_class{ return_type function_name(parameters(if any)){ class Inner_class{ } } } Sample Code – Explanation – The outer class ‘Outer_Demo’ encloses the method ‘hello(parameter)’ which is a parameterized function with a ‘final’ ‘int’ variable ‘param’, and the inner class ‘Inner_Demo’. The inner class further has a ‘void’ ‘inner’ method which prints the value of the ‘param’ variable as obtained by the inner class. Upon compilation and execution , the following code prints the value of ‘param’ as accepted by the ‘hello()’ function. A Variation of the above code can be as follows – Sample Code –
  • 9. Explanation – The outer class ‘Outer_Demo’ encloses the method ‘main()’ which is the main function of the outer class. The inner class ‘Inner_Demo’ is declared inside the main method and a ‘static’ ‘final’ ‘param’ variable is initialized. Then another function ‘inner()’ is declared which prints the value of the ‘param’ variable. Upon compilation and execution, the following code prints the value of ‘param’ as initialized within the inner class. If the variable is declared without being static then there would be a compilation error. c) Anonymous Inner classes : Local classes with no name are called Anonymous classes. It helps to make code more concise by allowing us to declare and instantiate a class at the same time. It is used when a local class is to be used only once in the code. It is often used to override method of a class or interface. They are much like expressions rather than a class declaration and they have the same access to local variables of the enclosing scope as local classes. Anonymous classes can have static members provided only if they are ‘final’ variables. Its Syntax is as follows – public class SuperClass { public void doIt() { System.out.println("SuperClass doIt()"); } } (Inside a driver class within a main function) SuperClass instance = new SuperClass() { public void doIt() { System.out.println("Anonymous class doIt()"); } }; instance.doIt(); Explanation – Compiling and executing this code would result in “Anonymous class doIt()” being printed to System.out. The anonymous class subclasses (extends) SuperClass and overrides the doIt() method.
  • 10. Sample Code – Explanation – The above code is for the inner anonymous class to perform EventHandling. Here, ‘Button’ is the outer class and the anonymous class is created when the instance of the Button class, ‘btn’ calls the ‘setOnAction()’ method, to perform the Event Handling. iv) Static Nested Classes A static nested class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class. The Syntax of a Static Nested Class is – class Outer_class{ static class Inner_class{ } } Sample Code –
  • 11. Explanation – The outer class ‘Outer_Demo’ encloses the static nested class ‘Nested_Demo’, which in turn has a function ‘my_method’ which is simply placed to print a line. Then, the main method is used to instantiate the nested static class. The Syntax for doing so is – Outer_class.Nested_class object = new Outer_class.Nested_class(); Then the object is used to access the enclosed function which is non-static. Had it been static a direct metod name would invoke the function. On compiling and executing the code, the result is – v) Difference between Static and Non-static Nested Classes a) Nested static class doesn't need reference of Outer class, but non-static nested class or Inner class requires the Outer class reference. One cannot create instance of Inner class without creating instance of Outer class. This is by far most important thing to consider while making a nested class static or non static. Syntactically, Outer_class.Inner_class method_name = new Outer_Class.Inner_Class(); for static inner class object creation, and Outer_class.Inner_class method_name = new Outer_Class.new Inner_Class(); for non-static inner class object creation. b) Static class is actually static member of class and can be used in static context e.g. static method or static block of Outer class. c) Another difference between static and non static nested class is that one cannot access non static members e.g. method and field into nested static class directly. If it is done an error like "non static member cannot be used in static context" is displayed. While Inner class can access both static and non static member of Outer class. vi) Advantages of Nested Classes a) It is a way of logically grouping classes that are only used in one place. b) Can access all the members of the outer class including private data members and methods. c) Can be declared private, public, protected or package private, unlike regular classes that can be only declared public or package private.
  • 12. d) It increases encapsulation as it can itself be declared private and still access the outer class’ private members. e) It can lead to more readable and maintainable code as it places the code closer to where it is used. vii) Disadvantages of Nested Classes a) Anonymous classes may make code difficult to read and understand. b) Classes contain a mixture of purposes, and thereby, no longer remain specific and easily understandable. c) Inner classes may even cause security concerns. 4. Conclusion JAVA being an Object Oriented Programming (OOP) Language offers us the priced facet of encapsulation. This encapsulation can also be extended to as far as the classes themselves which can also be encapsulated into yet other enclosing classes. Thus, the concept of Nested classes. Besides, all the advantages of Nested classes as stated above, they also help us to produce more concise and logically grouped code, which are far more readable and easy to understand. Nested classes especially anonymous classes are especially useful as their references are only created when required, thereby, leading to the more effective usage of memory as a resource. Thus, Nested classes are a valuable asset to JAVA programming language, which caters to the unique style of programming of each programmer and thereby, provides the programmer with a lot of tools to foster their unique style and making programming a more enjoyable experience. But as with all great powers, comes great responsibilities, Nested classes should be used wisely as, they can sometimes, make the code difficult to read and understand, and in some situations, inner classes may even cause security concerns. 5. References i) THE COMPLETE REFERENCE TO JAVA by Herbert Schildt, TATA McGRAW HILL publication ii) https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html iii) http://www.java67.com/2012/10/nested-class-java-static-vs-non-static-inner.html iv)https://dzone.com/articles/nested-classes-in-java v) https://www.javatpoint.com/java-inner-class vi)https://www.geeksforgeeks.org/nested-classes-java/