Java Program to Illustrates Use of Instance Inner Class

This is a Java Program to Illustrates Use of Instance Inner Class. An inner class has access to all of the members of its enclosing class, but the reverse is not true.

Here we access the members of the outer class named outer in the inner class named inner. But the members of inner class cannot be used by the outer class.

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

  1. class Outer 
  2. {
  3.     int outer_x = 100;
  4.     void test() 
  5.     {
  6.         Inner inner = new Inner();
  7.         inner.display();
  8.     }
  9.     class Inner 
  10.     {
  11.         int y = 10; 
  12.         void display() 
  13.         {
  14.             System.out.println("display: outer_x = " + outer_x);
  15.         }
  16.     }
  17.     void showy() 
  18.     {
  19.         System.out.println(y); // error, y not known here!
  20.     }
  21. }
  22. class InnerDemo 
  23. {
  24.     public static void main(String args[]) 
  25.     {
  26.         Outer outer = new Outer();
  27.         outer.test();
  28.     }
  29. }

Output:

$ javac InnerDemo.java
$ java InnerDemo 
 
display: outer_x = 100

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.