The following program uses an inner class named Anonymous which itself extends its enclosing class Main.
package name;
public class Main
{
private final String name;
Main(String name)
{
this.name = name;
}
private String name()
{
return name;
}
private void reproduce()
{
new Anonymous().printName();
}
private class Anonymous extends Main
{
public Anonymous()
{
super("reproduce");
}
public void printName()
{
System.out.println(name());
}
}
public static void main(String[] args)
{
new Main("main").reproduce();
}
}
The only statement in the main() method invokes the constructor of the outer class Main supplying a string main and just then the method reproduce() is being called.
The reproduce method contains the statement new Anonymous().printName(); which invokes the printName() method on the Anonymous class object. The super(); constructor is supplying a new string reproduce to its enclosing super class Main.
Accordingly, the statement within the printName method System.out.println(name()); should display the string reproduce rather than main but it always displays the string main. Why is it so?
Because you’ve declared
Main.name()asprivate, so it’s not visible as a superclass method. It is, however, visible as a method ofAnonymous‘s enclosing class, so it is invoked on the enclosing object.So if you declare
Main.name()aspublicorprotected, you will indeed see"reproduce".Alternatively, if you declare
Anonymousasstatic, it no longer compiles.