Java Program to Illustrates Use of Static Inner Class

This is a Java Program to Illustrates Use of Static Inner Class.

We made a Outer class and define a static Inner class in it. We define a non static method as show() method in inner class and we try to call this method by inner class object and outer class object and we get the desired output.

Here is the source code of the Java Program to Illustrates Use of Static Inner Class. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. public class Outer 			//outer class
  2. {
  3.     int x = 10;
  4.     static int y = 20;
  5.     static class Inner 			//static inner class
  6.     {
  7.         void show()		        // non static method in static inner class
  8.         {
  9.             System.out.println(y);
  10.             //  System.out.println(x);  error :  non-static variable x cannot be referenced from a static context
  11.         }
  12.     }
  13.     public static  void main(String... s)
  14.     {
  15.         System.out.println("'In main method'. The vlaue of static data member of outer class is :"+y);
  16.         //  System.out.println(x);                     error:  non-static variable x cannot be referenced from a static context
  17.         System.out.println("Inner class method accessed by Inner class object ");
  18.         Inner i = new Inner();
  19.         i.show();
  20.         System.out.println("Inner class method accessed by outer class object ");
  21.         Outer.Inner o = new Outer.Inner();
  22.         o.show();
  23.     }
  24. }

Output:

$ javac Outer.java
$ java Outer
 
'In main method'. The vlaue of static data member of outer class is :20
Inner class method accessed by Inner class object 
20
Inner class method accessed by outer class object 
20

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.