PROGRAMMING

MINTE9
REMEMBERS




Last update:   23-07-2021

Nested Classes

Java allows a class within another class (nested classes). It increases encapsulation and can lead to more readable and maintainable code.
 RunCode
class App {

    public static void main(String[] args) {
        
        System.out.println(
            OuterClass.InnerClass.y // 20
        );
    }
}

class OuterClass {

    int x = 10;
    static class InnerClass {
        static int y = 20;
    }
}
... 7 lines
˄˄˄
! The nested class can use fields from Outer Class. The nested classes are the only classes that can be declare static.
 RunCode
class App {

    public static void main(String[] args) {
        
        A.B.run(); // 10
    }

    static class A {

        static int a = 10;
        static class B {
            public static void run() {
                System.out.println(a); // field from Outer Class
            }
        }
    }
}
... 7 lines
˄˄˄

Questions    
16. Final
15 . Nested Classes
Last update:   23-07-2021

        A B C D E F
🔔
1/1