user3663882
user3663882

Reputation: 7357

Accessing a private field from within the class refuses to compile

This example does not compile:

public class Test{
    private LinkedList<Integer> lst = new LinkedList<>();

    public static Test of(int i){
        return new Test(){{
            this.lst.addFirst(i);
        }};
    }
}

DEMO

But this does:

public class Test{
    private LinkedList<Integer> lst = new LinkedList<>();

    public static Test of(int i){
        Test t = new Test();
        t.lst.addFirst(i);
        return t;
    }
}

DEMO

Why? In both cases we access a private member from the class body.

Upvotes: 0

Views: 50

Answers (2)

Sanjeev Saha
Sanjeev Saha

Reputation: 2652

When you define:

return new Test(){{
      this.lst.addFirst(i);
}};

You create an anonymous sub class of Test. The access specifier of lst is private. So you may not access a private member of super class from a sub class. So you get compilation-error.

But when you declare:

Test t = new Test();
t.lst.addFirst(i);

You are accessing the private member lst from inside a method i.e. public static Test of(int i) of the class to which the private member belongs. So you do not get compilation-error.

Upvotes: 1

Seelenvirtuose
Seelenvirtuose

Reputation: 20608

With the code

new Test() { ... }

you actually declare and instantiate an anonymous subclass of Test. And a subclass simply does not have access to its parent's private members.

See JLS §15.9 (Class Instance Creation Expressions) and JLS §15.9.5 (Anonymous Class Declarations) for more information

Upvotes: 5

Related Questions