World's most popular travel blog for travel bloggers.

Static Nested Classes

, , No Comments
Static nested classes
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.
They are accessed using the enclosing class name.
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
     new OuterClass.StaticNestedClass();
// Java program to demonstrate accessing
// a static nested class
// outer class
class OuterClass
{
    // static member
    static int outer_x = 10;
     
    // instance(non-static) member
    int outer_y = 20;
     
    // private member
    private static int outer_private = 30;
     
    // static nested class
    static class StaticNestedClass
    {
        void display()
        {
            // can access static member of outer class
            System.out.println("outer_x = " + outer_x);
             
            // can access display private static member of outer class
            System.out.println("outer_private = " + outer_private);
             
            // The following statement will give compilation error
            // as static nested class cannot directly access non-static membera
            // System.out.println("outer_y = " + outer_y);
         
        }
    }
}
// Driver class
public class StaticNestedClassDemo
{
    public static void main(String[] args)
    {
        // accessing a static nested class
        OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
         
        nestedObject.display();
         
    }
}
Output:
outer_x = 10
outer_private = 30

0 comments:

Post a Comment

Let us know your responses and feedback