0 votes
1 view
in Java by (3.9k points)

What is the difference between an inner class and a static nested class in JAVA? Does design/implementation play a role in choosing one of these?  

1 Answer

0 votes
by (46.1k points)

 A Class which is declared inside another class is called nested class. Like any other member of a class, you can declare a nested class as static. A class which is declared as static inside another class is called a static nested class. A class that is declared without using static is called inner class or non-static nested class.

A static nested class is class level like other static members of the outer class. Whereas, an inner class is tied to an instance and it can access instance members of the enclosing class.

Example:

Inner class:

public class Q

{

   private int count;

   public void setCount(int count) {

       this.count = count;

   }

   class W

{

       private int total;

       public void setTotal(int total) {

           this.total = total;

       }

   }

}
Static Class:

public class Q

{

   private int count;

   public void setCount(int count)

{

       this.count = count;

   }

   static class W

{

       private int total;

       public void setTotal(int total) {

           this.total = total;

       }

   }

}

from the examples above an inner class which is defined in a static context doesn't have an enclosing instance. 

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...