Home Accessing static nested classes through references to outer class members
Reply: 2

Accessing static nested classes through references to outer class members

Cedric
1#
Cedric Published in 2018-01-12 19:17:58Z

I'm a beginner struggling with nested classes in general. Here is the first of what will likely amount to several questions on this subject.

In Java, why can't a static nested class be accessed through a reference to an object of the outer class, like other static members.

For example,

class program {
     public static void main(String[] args) {
          outerClass outerClassRefVar = new outerClass();
          int k;
          //k = outerClassRefVar.innerClass.i; doesn't compile
          k = outerClassRefVar.j; //does compile
     }
}

class outerClass {
     static class innerClass {
          static int i = 1;
     }
     static int j = 1;
}

...but innerClass and j are both static members of outerClass

tsolakp
2#
tsolakp Reply to 2018-01-12 19:41:35Z

innerClass is just like any Class and is not a static member of any class including outerClass. The only difference with innerClass is that you reference it from outside outerClass using fully qualified name outerClass.innerClass.

This works: outerClass.innerClass.i (BTW use proper Java class naming to avoid confusion with variable names).

dherediat
3#
dherediat Reply to 2018-01-12 19:25:19Z

My solution is this... If you want do it you must put all references of that static nested class with static property. Read also something of this Java inner class and static nested class

public class MyClass {
    public static void main(String args[]) {
       method1();
       System.out.println("main:   " + NestedClass.data1);
    }
    public static void method1(){
        System.out.println("method1:  "+ NestedClass.data1);
    }
    static class NestedClass{
        static String data1 = "Something";
    }
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.432067 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO