Yishu Fang
Yishu Fang

Reputation: 9958

Why a subclass of a nested class cannot access the nesting class's private field here?

Java code like this:

public class A {
        private static int a;

        public static class B {
                static void funcc() {
                        a = 3;
                }
        }
}


public class C extends A.B {
        public void func() {
                a = 1;
        }
}

When I try to compile it, an error occurs:

C.java:3: error: cannot find symbol
                a = 1;
                ^
  symbol:   variable a
  location: class C
1 error

Why this happens?

Upvotes: 0

Views: 317

Answers (3)

Ted Hopp
Ted Hopp

Reputation: 234795

Nested class B has access to all of the fields and methods of it's enclosing because it is a member of A. Subclasses of B (that are not members of A) do not have that access.

Upvotes: 2

Jim Garrison
Jim Garrison

Reputation: 86764

B is static. This makes it equivalent to declaring it at top level. It is not a nested class and does not have access to anything private in its lexically containing class.

Upvotes: 3

Cory Kendall
Cory Kendall

Reputation: 7304

Internal classes don't extend their containing class; they are a class in their own right.

In your example, B is a class which has no methods and no fields. It doesn't have a variable a.

However you could access the variable a inside of the B class, but this is only because a is in its closure; it can peak at A's variables, which is the power of an internal class.

Upvotes: 0

Related Questions