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/