public class OuterClass {
private static String staticMessage = “Static message from OuterClass”;
private String nonStaticMessage = “Non-static message from OuterClass”;
// Static nested class
static class StaticNestedClass {
void display() {
// Accessing static member of OuterClass
System.out.println(“Accessing from StaticNestedClass: ” + staticMessage);
// Cannot access non-static members of OuterClass
// System.out.println(“Non-static message: ” + nonStaticMessage); // This would cause an error
}
}
// Non-static nested class (Inner class)
class InnerClass {
void display() {
// Accessing both static and non-static members of OuterClass
System.out.println(“Accessing from InnerClass:”);
System.out.println(“Static message: ” + staticMessage);
System.out.println(“Non-static message: ” + nonStaticMessage);
}
}
public static void main(String[] args) {
// Create an instance of StaticNestedClass
StaticNestedClass staticNested = new StaticNestedClass();
staticNested.display();
// Create an instance of InnerClass
OuterClass outer = new OuterClass();
InnerClass inner = outer.new InnerClass();
inner.display();
}
}
Leave a Reply