Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A twisted inner class in Java

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?

like image 806
Lion Avatar asked Nov 16 '11 23:11

Lion


People also ask

What is a inner class in Java?

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.

What is abstract inner class in Java?

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).

What is nested class in Java with example?

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.


1 Answers

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.

like image 81
Oliver Charlesworth Avatar answered Sep 23 '22 16:09

Oliver Charlesworth