minte9
LearnRemember



Encapsulation

Java allows a class within another class (nested classes).
 
/**
 * Nested classes increases encapsulation.
 * They can lead to more readable and maintainable code.
 */

package com.minte9.oop.nested_classes;

public class Encapsulation {
    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;
    }
}

Static

The nested classes are the only classes that can be declare static.
 
/**
 * Only nested classes can be declared as static classes.
 * Inner classes can use fields from outer class.
 */

package com.minte9.oop.nested_classes;

public class Static {
    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
            }
        }
    }
}



  Last update: 382 days ago