06 - Nested Class
06 - Nested Class
Tanjina Helaly
NESTED CLASS
Java inner class or nested class is a class i.e.
declared inside a class or interface.
We use inner classes to logically group classes and
interfaces in one place so that it can be more readable
and maintainable.
Additionally, it can access all the members of outer
class including private data members and methods.
Structure
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
ADVANTAGE OF JAVA NESTED CLASSES
There are few advantages of inner classes in java.
They are as follows:
1) Nested classes represent a special type of
relationship that is it can access all the members
(data members and methods) of outer class
including private.
2) Nested classes are used to develop more
readable and maintainable code because it
logically group classes and interfaces in one place
only.
3) Code Optimization: It requires less code to write.
4) Encapsulation: it increases encapsulation. Inner
class can be private. Also inner class can access the
private member of outer class.
TYPES OF NESTED CLASSES
There are two types of nested classes.
Non-static nested class(inner class)
a)Member inner class
b)Anonymous inner class
p.display();
p.display("3"); // Ok
p.display(3); // error: The method display(String) in the type Person
is not applicable for the arguments (int)
}
}
LOCAL INNER CLASS
LOCAL INNER CLASS
A class i.e. created inside a method is called
local inner class in java.
If you want to invoke the methods of local inner
class, you must instantiate this class inside the
method.
Local inner class cannot be invoked from
outside the method.
Local inner class cannot access non-final
local variable till JDK 1.7. Since JDK 1.8, it
is possible to access the non-final local
variable in local inner class.
LOCAL INNER CLASS - EXAMPLE
class localInner2{
private int data=30;//instance variable
void display(){
int value=50;//local variable must be final till jdk 1.7 only
class Local{
void msg(){System.out.println(value);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
localInner2 obj=new localInner2();
obj.display();
}
}
STATIC NESTED CLASS
STATIC NESTED CLASS
A static class i.e. created inside a class is called static
nested class in java.
It cannot access non-static (instance) data members and
methods. It can be accessed by outer class name.
It can access static data members of outer class including
private.
In order to access the instance method of Inner class
Need to create the instance of static nested class because it
has instance method msg().
But you don't need to create the object of Outer class
because nested class is static and static properties,
methods or classes can be accessed without object.
If you have the static member inside static nested
class,
you don't need to create instance of static nested class.
STATIC NESTED CLASS - EXAMPLE
class TestOuter1{
static int data=30;