Java Nested Classes Explained: Static vs Non-Static

Hello Java Developers, 🚀 Day 10 – Java Revision Series Today’s topic dives into nested classes in Java and clarifies a common source of confusion. ❓ Question What is the difference between a static nested class and a non-static (inner) class in Java? ✅ Answer Java allows classes to be defined inside another class. These nested classes are mainly of two types: Static Nested Class Non-Static Nested Class (Inner Class) The key difference lies in their relationship with the outer class instance. 🔹 Static Nested Class A static nested class is associated with the outer class itself, not with an object of the outer class. class Outer { static class StaticNested { void display() { System.out.println("Static nested class"); } } } Characteristics: Does not require an instance of the outer class Can access only static members of the outer class Behaves like a regular top-level class (just namespaced) Usage: Outer.StaticNested obj = new Outer.StaticNested(); ✅ Better memory efficiency ✅ Cleaner design when no outer instance is needed 🔹 Non-Static Nested Class (Inner Class) A non-static nested class is tightly bound to an instance of the outer class. class Outer { class Inner { void display() { System.out.println("Inner class"); } } } Characteristics: Requires an outer class object Can access both static and non-static members of the outer class Holds an implicit reference to the outer object Usage: Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); ⚠️ Higher memory overhead due to outer reference #Java #CoreJava #NestedClasses #StaticKeyword #OOP #JavaDeveloper #LearningInPublic #InterviewPreparation

  • text, letter

To view or add a comment, sign in

Explore content categories