-1

Please review this code which compiles fine :

class OuterClass {

    String a = "A";
    String b = "B";
    String c = "C";


    public static class StaticInnerClass {

    }

    public String stringConCat() {
        return a + b + c;
    }
}

this is as i expect as the inner class can access the outer classes attributes. But now when i try the same code but assigning a outer attribute to inner attribute the system complains:

class OuterClass {

    String a = "A";
    String b = "B";
    String c = "C";


    public static class StaticInnerClass {
        String x = a; //this can not be done, why ?
    }

    public String stringConCat() {
        return a + b + c;
    }
}

the error/warning at compile time is: Non-static field a cannot be referenced from a static context.

is it because in the method stringConCat() you actually need an instance to call the method (post constructor call) so its allowed ? Whereas, in the second example there is no real instance so it treats it as a static reference ?

I've read I thought inner classes could access the outer class variables/methods? but its still not sinking. Can someone help?

Community
  • 1
  • 1
j2emanue
  • 60,549
  • 65
  • 286
  • 456
  • There is no inner class here. 'static inner' is a contradiction in terms. What you have here is a static *nested* class. – user207421 Jan 07 '16 at 01:01

1 Answers1

2

The key is in your error message: "Non-static field a cannot be referenced from a static context."

inner classes can access outer class variables, but your nested class is static, not inner, and the variable is not static. Either make the variable static, or make the nested class non-static.

user207421
  • 305,947
  • 44
  • 307
  • 483
Krease
  • 15,805
  • 8
  • 54
  • 86
  • 1
    oh i get what your saying now Chris good point. My class is static and im trying to access a non-static value which is not permitted and makes no sense as outer class can have many instances and it would not know which "a" to give me. Not sure why i got a downvote from someone for asking lol .Thanks a bunch. – j2emanue Jan 07 '16 at 00:57
  • 1
    'Static inner' is a contradiction in terms. This is a static nested class. – user207421 Jan 07 '16 at 01:10