How do you use inner and nested classes with a simple code example?

In Java, inner classes are defined within the body of another class, while nested classes are defined as static members of a class. Inner classes have access to their enclosing class's members, while nested classes do not. Here's a simple example demonstrating both types of classes:

class Outer { private String outerField = "Outer Field"; // Inner class class Inner { void display() { System.out.println("Accessing: " + outerField); } } // Nested static class static class Nested { void display() { System.out.println("This is a static nested class."); } } } public class Main { public static void main(String[] args) { Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); inner.display(); // Accessing: Outer Field Outer.Nested nested = new Outer.Nested(); nested.display(); // This is a static nested class. } }

Java inner class nested class example programming