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"?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With