Java Basic Tutorial
Java Advance Tutorial
An inner class in Java is a class that is defined within another class. Inner classes have access to the members (fields, methods) of the outer class, even if they are private. Inner classes help logically group classes that are only used in one place, making your code more readable and maintainable.
There are four types of inner classes in Java:
A non-static inner class is associated with an instance of the outer class. It can access the instance variables and methods of the outer class.
class OuterClass { private int outerVar = 10; class InnerClass { void display() { System.out.println("Outer variable: " + outerVar); } } }
Try it yourself
A static nested class is a static member of the outer class. It can only access static members of the outer class. It does not need an instance of the outer class to be instantiated.
class OuterClass { static int outerStaticVar = 20; static class StaticInnerClass { void display() { System.out.println("Outer static variable: " + outerStaticVar); } } }
Try it yourself
A local inner class is defined inside a method or a block of code, and it can only be used within that method/block. It cannot have access to the instance variables of the outer class unless they are declared final
or effectively final
.
Try it yourself
An anonymous inner class is a special type of inner class that does not have a name. It is used to create instances of classes that may not be reused elsewhere. These classes are typically used to provide an implementation for interfaces or extend a class in a one-off manner.
Try it yourself
Try it yourself