This program defines an outer class called OuterClass that contains a static field called staticField and an instance field called instanceField. It also defines two inner classes: InnerStaticClass, which has a method that prints the value of the static field, and InnerInstanceClass, which has a method that prints the value of the instance field.
The main method creates an instance of the outer class, outer, and then creates instances of both inner classes, innerInstance and innerStatic. It then uses these instances to access the instance and static fields, respectively.
Note that the InnerInstanceClass requires an instance of the outer class in order to be created, whereas the InnerStaticClass can be created without an instance of the outer class. This demonstrates the difference between inner instance classes and inner static classes.
public class OuterClass { private static int staticField = 10; private int instanceField = 20; public static class InnerStaticClass { public void printStaticField() { System.out.println("Static field: " + staticField); } } public class InnerInstanceClass { public void printInstanceField() { System.out.println("Instance field: " + instanceField); } } public static void main(String[] args) { // Create an instance of the outer class OuterClass outer = new OuterClass(); // Create an instance of the inner instance class OuterClass.InnerInstanceClass innerInstance = outer.new InnerInstanceClass(); // Create an instance of the inner static class OuterClass.InnerStaticClass innerStatic = new OuterClass.InnerStaticClass(); // Access the instance field from the inner instance class innerInstance.printInstanceField(); // Access the static field from the inner static class innerStatic.printStaticField(); } }
Instance field: 20 Static field: 10
Comments
Post a Comment