Unexpected behavior when changing the modifier of a member variable in connection with an inner class

Lars Herschke lhersch at dssgmbh.de
Tue May 5 14:50:41 UTC 2020


Oh, i'm seeing attachments don't work in the mailing list. So here is
the code.

public class Outer
{
    private int x;
            int y;

    private class Inner extends Outer
    {
        void work()
        {
            System.out.println("work: out     private x: outer.x=" +
Outer.this.getX() + ", inner.x=" + this.getX() + ", non-qualified.x=" + x);
            System.out.println("work: out non-private y: outer.y=" +
Outer.this.getY() + ", inner.y=" + this.getY() + ", non-qualified.y=" + y);
            System.out.println("work: set
       non-qualified.x=3");
            x = 3;
            System.out.println("work: set
       non-qualified.y=3");
            y = 3;
        }
    }

    void setX(int value)
    {
        x = value;
    }

    int getX()
    {
        return x;
    }

    void setY(int value)
    {
        y = value;
    }

    int getY()
    {
        return y;
    }

    public static void main(String... args) {
        Outer out = new Outer();
        Outer.Inner inn = out.new Inner();
        System.out.println("main: set                outer.x=1");
        out.setX(1);
        System.out.println("main: set                           inner.x=2");
        inn.setX(2);
System.out.println("main: set                outer.y=1");
        out.setY(1);
        System.out.println("main: set                           inner.y=2");
        inn.setY(2);
        inn.work();
        System.out.println("main: out     private x: outer.x=" +
out.getX() + ", inner.x=" + inn.getX());
        System.out.println("main: out non-private y: outer.y=" +
out.getY() + ", inner.y=" + inn.getY());
    }
}


> Hello,
> 
> there is a small test program in the appendix that I would like to know
> about, bug or not.
> The output of the program is the following for me.
> 
> 
> main: set                outer.x=1
> main: set                           inner.x=2
> main: set                outer.y=1
> main: set                           inner.y=2
> work: out     private x: outer.x=1, inner.x=2, non-qualified.x=1
> work: out non-private y: outer.y=1, inner.y=2, non-qualified.y=2
> work: set                                      non-qualified.x=3
> work: set                                      non-qualified.y=3
> main: out     private x: outer.x=3, inner.x=2
> main: out non-private y: outer.y=1, inner.y=3
> 
> 
> Why does the interpretation of unqualified variables change here,
> depending on the modifier.
> 
> Is this behavior desired and described somewhere or is it an error.
> 
> Thanks, Lars
> 



More information about the discuss mailing list