What is Nested and Inner Classes in Java Language?

                                 Nested and Inner Classes

It is possible in Java language to define a one class within another class these classes are called as nested classes.


Scope of Nested Classes:

The Scope of all Nested class is bounded by the scope of its inserting  class.

Example:

If  B class is Define within class A then the class B is only Known to A and not outside of class A and the scope is in class only class A.


Nested class has access all members including private members. But inserting class does not have access the nested class members.

Type of Nested Classes:

There are two types of Nested classes:
  1. Static Nested Class.
  2. Non-Static Nested Class.


1.Static Nested Class:

Static Nested class is one in which static modifier applied. Member of inserting class must access by an object. Static Nested Class can't refer to members of its inserting class directly because of this restriction , static nested classes are rarely used.


2. Non-Static Nested Class:

Most important type of nested class is the inner class. An inner class is a non-static nested class.
It can access all Methods and variables of its outer class and also refer them directly int same way that other non-static Members of outer class do.



class Outer{
int outer;
void Test(){
Inclass in = new Inclass();
in.Display();
}

classInclass{ //this is inner class

void Display(){

System.out.println("Display Outer Variable Value"+outer);
}
}
}

class Demo{
public static void main(String args[]){
Outer out = new Outer();
out.Test();
}
}




Comments

Popular posts from this blog

Inheritance in Java

Operators in Java Language?

Type Casting or Conversion in Java