Inner Class, Static Inner Class and Anonymous Inner Class

 01) Inner Class

In Java, inner class is a class that defined within another class. Inner classes provide better encapsulation, organization and useful when you want to logically group classes that are only used in one place. Inner classes are able to access the outer class's methods and variables, if they are even private. They often used to be readable and maintainable codes.

In Java, there are several inner classes among those, the three inner classes that i chose are as below;

  1. Normal Inner Class (Non-Static Inner Class)
  2. Static Inner Class
  3. Anonymous Inner Class




1. Normal Inner Class (Non-Static Inner Class)

Inner class is a class that is declared within the outer class. It can access the outer class's methods and variables, even if it is private.

Example:

class Outer {
    private String message = "Hello from Inner Class!";

    class Inner {
        public void showMessage() {
            System.out.println(message); 
        }
    }
}

public class Test {
    public static void main(String[] args) {
        Outer outer = new Outer();              
        Outer.Inner inner = outer.new Inner();  
        inner.showMessage();                   
    }
}




2. Static Inner Class

In Static inner class, the class is defined within another class but marked with the "static" keyword. It is not required to create an instance of the outer class and there is no ability to directly access non-static methods and variables from the outer class. It can be access without creating an object in the outer class.

class Outer {
    private static String message = "Hello from Static Inner Class!";

    static class Inner {
        public void showMessage() {
            System.out.println(message); 
        }
    }
}

public class Test {
    public static void main(String[] args) {
        Outer.Inner inner = new Outer.Inner();  
        inner.showMessage();                    
    }
}



3. Anonymous Inner Class

Anonymous inner class is a special type of inner class in java that does not have a name. It is created when we want a temporary class for a specific task and we need to use it only once. Instead of creating a new class, we write the class and create an object in one step. It is usually use to implement an interface or extend a class.

Example:

interface Greeting {
    void sayHello();
}

public class Test {
    public static void main(String[] args) {
        Greeting greeting = new Greeting() {
            public void sayHello() {
                System.out.println("Hello from Anonymous Inner Class!");
            }
        };
        greeting.sayHello();  
    }
}






Comments

Popular posts from this blog

Blocking and Non-Blocking Operations

OOP Concepts in Java.