Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The method of an anonymous class behaves unexpectedly

Tags:

public class Solution {
    private String name;

    Solution(String name) {
        this.name = name;
    }

    private String getName() {
        return name;
    }

    private void sout() 
    {
        new Solution("sout")
        {
            void printName() 
            {
                System.out.println(getName());
            }
        }.printName();
    }

    public static void main(String[] args) {
        new Solution("main").sout();
    }
}

The method of an anonymous class behaves unexpectedly. How to make method sout to print "sout", now it prints "main"?

like image 824
kurumkan Avatar asked Mar 19 '16 21:03

kurumkan


1 Answers

The problem is that String getName() is private.

What this means is that it is inaccessible to methods of derived classes.

However, the anonymous derived class is not only derived, but it is also an inner class. As such, the class has access to private members of the outer class. That is why main gets printed, not sout.

All you need to do to make this work is to make the method non-private: default access, protected, or public would work fine.

Demo.

like image 118
Sergey Kalinichenko Avatar answered Dec 01 '22 11:12

Sergey Kalinichenko