Sobes.tech
Junior — Middle

Mis vahe on sisemises klassi ja sisemisse klassi programmeerimises?

sobes.tech AI

Vastus AI-lt

In Java (and in Android) a nested class is any class declared within another class. Nested classes come in two types:

  1. Static nested class — declared with the static modifier. It does not have direct access to the non-static members of the outer class.
  2. Inner class — a nested class without the static modifier. It is associated with an instance of the outer class and has access to its non-static fields and methods.

Example:

class Outer {
    private int outerField = 10;

    static class StaticNested {
        void print() {
            // Cannot directly access outerField
            System.out.println("Static nested class");
        }
    }

    class Inner {
        void print() {
            // Can access outerField
            System.out.println("Inner class, outerField = " + outerField);
        }
    }
}

The main difference is that the inner class is associated with an object of the outer class and can access its non-static members, while the static nested class cannot.