Sobes.tech
Middle

What are the features of using nested classes, including static and inner classes? What is the difference between them?

sobes.tech AI

Answer from AI

Nested classes allow logical grouping of classes, increasing encapsulation and code readability.

Features:

  • Encapsulation: Nested classes have access to the private members of the outer class.
  • Logical grouping: Related classes are placed together.
  • Readability: The code becomes more structured.

Differences between static and inner nested classes:

Characteristic Static nested class (static nested class) Inner class (inner class)
Access to outer class members Only to static members To all members (static and non-static)
Instance creation Does not require an instance of the outer class Requires an instance of the outer class
Use of this No access to this of the outer class Has access to this of the outer class (via OuterClass.this)
Syntax of definition With the static keyword Without the static keyword

Examples:

  • Static nested class:
    public class OuterClass {
        private static int staticVar = 10;
        private int instanceVar = 20;
    
        static class StaticNestedClass {
            void display() {
                // Access only staticVar
                System.out.println("Static var: " + staticVar);
                // Does not have access to instanceVar
                // System.out.println("Instance var: " + instanceVar); // Error
            }
        }
    }
    
  • Inner class:
    public class OuterClass {
        private static int staticVar = 10;
        private int instanceVar = 20;
    
        class InnerClass {
            void display() {
                // Access to all members
                System.out.println("Static var: " + staticVar);
                System.out.println("Instance var: " + instanceVar);
            }
        }
    }