Anonymous class method behaves unexpectedly

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(); } } 

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

+5
source share
2 answers

The problem is that String getName() is private .

This means that it is not available for derived class methods.

However, an anonymous derived class is not only retrieved, but also an inner class. Thus, the class has access to private members of the outer class. This is why main is printed, not sout .

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

Demo version

+3
source

Would you use

 System.out.println( super .getName()); 

You have an anonymous inner Solution class inside a Solution , so getName() implicitly referencing an external instance because the method is private.

You can also make getName secure rather than private.

The explanation is the ornery bit. getName displayed by an anonymous class due to scope, but since it is private, an anonymous class usually cannot reference getName on its own because it is actually a subclass.

In fact, the strange case is that you have a static nested subclass:

 class Example { private void sayHello() { System.out.println(); } static class Subclass extends Example { Subclass() { // This is a compiler error // because it tries to call sayHello() // on an enclosing instance which doesn't // exist (as if Subclass is an inner class). sayHello(); } } } 

I looked at the spec in my answer to the static case, which also explains why "main" is printed here: fooobar.com/questions/176752 / ....

+1
source

Source: https://habr.com/ru/post/1245395/


All Articles