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?
An inner class in Java is defined as a class that is declared inside another class. Inner classes are often used to create helper classes, such as views or adapters that are used by the outer class. Inner classes can also be used to create nested data structures, such as a linked list.
In simple words, a class that has no name is known as an anonymous inner class in Java. It should be used if you have to override a method of class or interface. Java Anonymous inner class can be created in two ways: Class (may be abstract or concrete).
In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation, and creates more readable and maintainable code.
Because you've declared Main.name()
as private
, so it's not visible as a superclass method. It is, however, visible as a method of Anonymous
's enclosing class, so it is invoked on the enclosing object.
So if you declare Main.name()
as public
or protected
, you will indeed see "reproduce"
.
Alternatively, if you declare Anonymous
as static
, it no longer compiles.
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