Learn Nested Classes In Java

Sharing is healthy !!

Hi!! In this post we will learn nested classes in java.

what is nested class?

Nested class is a class within another class. A nested class is a member of its enclosing class. As a member of the outer class, a nested class can be declared private, protected or package private. Basically nested class is divided into two categories:

  • static:¬†nested classes that are declared with static keyword are called static nested classes.
  • non static: nonstatic nested classes are called inner class.

Syntax:

class OuterClass
{
......
class NestedClass 
{
.....
} 
}

Example:

class OuterClass
{
.....
static class StaticNestedClass 
{
.....
}
class InnerClass
{
.....
}
}

Nested class is a member of its enclosing class. In the above example outer class can be declared with the public access modifier or package private access modifier. Package private access modifier means no modifier and inner class is a member of outer class. So we can declare inner class with private or public or protected or package private access modifiers. Static nested classes do not have access to other members of the enclosing class. Non static nested classes or inner classes have access to other members of enclosing class even if they are declared with the private access modifier. Let’s see code implementation,

Also Read –¬†Learn Operators In Java

public class ClassOuter {
 
int m;
 
public void showOuter(){
 
System.out.println("Showing outer class method : ");
 
}
 
static class NestedClass{
 
int n;
 
public void showNested(){
 
System.out.println("Showing showNested method : ");
 
}
 
}
 
class InnerClass{
 
int o;
 
public void showInner(){
 
System.out.println("Showing showInner method : "); 
 
}
 
}

}

Learn Nested Classes In Java: 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. A static nested class interacts with the instance members of its outer class(and other classes) just like any other top level class. In effect, a static nested class is behaviorally a top level class that has been nested in another top level class for packaging convenience. Let’s see its syntax,

Syntax:

class OuterClass
{
......
static class NestedClass 
{
.....
} 
}

Here you can see the “OuterClass”. Inside “OuterClass” we have defined “NestedClass”. This class is declared with static keyword, so this class is “NestedClass”. If “NestedClass” wants to access instance variable and instance methods of outer class it has to use object reference. This is how we can create instance of NestedClass,

OuterClass.NestedClass object = new OuterClass.NestedClass();

Now let’s see its code implementation,

public class ClassOuter {
 
private int out_Variable = 5;
private static int staticOutVariable = 100;
 
public void showOuter(){
 
System.out.println("showOuter method is called.....!");
 
}
 
public static void staticOuterDisplay(){
 
System.out.println("staticOuterDsiplay method is called.....!");
 
}
 
static class StaticNestedClass{
 
int in_Variable = 200;
 
public void showInner(){
 
System.out.println("showInner method is called.....");
System.out.println("in_Variable : " + in_Variable);
System.out.println("staticOutVariable : " + staticOutVariable);
staticOuterDisplay(); 
 
}

}

}
public class Nested_Demo {

public static void main(String[] args) {
 
ClassOuter.StaticNestedClass nestobj = new ClassOuter.StaticNestedClass();
nestobj.showInner();

}

}

Output:

Learn Nested Classes In Java


Learn Nested Classes In Java: non static nested class or inner class

A class which is defined inside another class is called the inner class. Inner class is associated with the instance of outer class. From inner class we can access outer class instance variable and outer class instance methods. Inner class cannot define any static members because inner class is associated with the instance of outer class. Objects that are instance of inner class can exist only within the instance of outer class.

Syntax:

class OuterClass
{
......
class InnerClass 
{
.....
} 
}

To create inner object first we have to create outer object like this,

OuterClass outObject = new OuterClass();

OuterClass.InnerClass inobject = outObject.new InnerClass();

Now let’s see code implementation,

public class ClassOuter {
 
private int out_Variable = 5; 
 
public void showOuter(){
 
System.out.println("showOuter method is called.....!");
 
}
 
class InnerClass{
 
int in_Variable = 10;
 
public void showInner(){
 
System.out.println("showInner method is called.....");
System.out.println("out_Variable : " + out_Variable);
System.out.println("in_Variable : " + in_Variable);
showOuter(); 
 
}
 
}

}
public class Nested_Demo {

public static void main(String[] args) {
 
ClassOuter outObj = new ClassOuter();
ClassOuter.InnerClass inObj = outObj.new InnerClass();
inObj.showInner();

}

}

Output:

Learn Nested Classes In Java


what are the access modifiers used in inner class?

For inner class we can apply public, private, protected and package private access modifier. Package private access modifier means no explicit modifier.


why should we use nested classes?

Let’s see why with an example,

class X
{
..... 
}
class Y
{
..... 
}

Here we have class X and class Y. And class Y is only useful for class X and class Y is not useful for any other classes in the application. In that case what we can do is, we can embed class Y inside class X,

class X
{
......
class Y 
{
.....
} 
}

In that way we can group above two classes in one place. Nested classes 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 embedded it in that class and keep that two together. Nesting such helper classes makes their package more streamlined. Nested classes can lead to more readable and maintainable code. Nesting small classes within top level classes places the code closer to where it is used.

By hiding class Y within class X, X class members can be declared with private and class Y can access them. This increases encapsulation. In addition, Y itself can be hidden from the outside world. Let’s see an example,

// Outer class

public class X
{
private int a = 5;
   
// Inner class

class Y
{
int b = 10;

public void showInner()
{

System.out.println("a : " + a);

}
} 
}
public class Nested_Demo {

public static void main(String[] args) {
 
X x = new X();
X.Y y = x.new Y();
y.showInner();

}

}

Output:

a : 5

There are two types of inner classes, they are,

  • Local classes
  • Anonymous classes

local class

Local classes are classes which are defined inside a block and we used to define local classes inside a method. Local class can access outer class member variables and local class can access method parameters and local variables.

Syntax:

class OuterClass
{
.....
public void someMethod()
{
.....
class LocalClass
{
.....
}
.....
} 
}

Example:

public class ClassOuter 
{ 
private String f_Name = "George"; 
 
public void show(String parameter)
{ 
String l_var = "Local Variable";
 
class LocalClass
{
String greet = "Welcome";
 
public void printMessage()
{
System.out.println("Hi " + greet + " " + f_Name);
System.out.println("Local Variable = " + l_var);
System.out.println("Parameter = " + parameter);
}
}
 
LocalClass lc = new LocalClass();
lc.printMessage();
}

}
public class Nested_Demo {

public static void main(String[] args) {
 
ClassOuter outObj = new ClassOuter();
outObj.show("This is parameter");

}

}

Output:

Learn Nested Classes In Java

Note:

Inside local class we cannot declare static variable and static methods.


Anonymous classes

A class that has no name is known as anonymous inner class. It should be used only if you have to override methods of class. Class maybe abstract class or concrete class.

Example:

abstract class Person 
{
abstract void run();
}
public class Employee {

public static void main(String[] args) 
{
Person p_Ref = new Person() 
{ 
@Override
void run() 
{
System.out.println("Running too fast!!");
}
};
p_Ref.run();
}

}

Output:

Running too fast!!

As you can see in the above example, a class is created but its name is decided by the compiler which extends the Person class and provides the implementation of the run() method. An object of anonymous class is created that is referred by “p_Ref” reference variable of Person type.

Sharing is healthy !!

Leave a Reply

Your email address will not be published.