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.
public class Outer //outer class
{
int x = 10;
static int y = 20;
static class Inner //static inner class
{
void show() // non static method in static inner class
{
System.out.println(y);
// System.out.println(x); error : non-static variable x cannot be referenced from a static context
}
}
public static void main(String... s)
{
System.out.println("'In main method'. The vlaue of static data member of outer class is :"+y);
// System.out.println(x); error: non-static variable x cannot be referenced from a static context
System.out.println("Inner class method accessed by Inner class object ");
Inner i = new Inner();
i.show();
System.out.println("Inner class method accessed by outer class object ");
Outer.Inner o = new Outer.Inner();
o.show();
}
}
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
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Check Programming Books
- Practice BCA MCQs
- Apply for Computer Science Internship
- Practice Information Technology MCQs
- Apply for Java Internship