user1396008
user1396008

Reputation:

What is an anonymous inner class?

When I tried to do some sample on an abstract class in Java I accidentally got some thing like anonymous inner class in Eclipse.

I have pasted the piece of code below. I don't understand how the abstract class is related to anonymous class.

package com.Demo;

abstract class OuterClass {
    abstract void OuterClassMethod();
}

public abstract class InnerClass extends OuterClass {
    public static void main(String[] args) {
        InnerClass myInnerClass = new InnerClass() {
            @Override
            void OuterClassMethod() {
                int OuterClassVariable = 10;
                System.out.println("OuterClassVariable" + " " + OuterClassVariable);
            }
        };
    }
}

Upvotes: 1

Views: 231

Answers (3)

Lee White
Lee White

Reputation: 3739

Basically, an anonymous class is an implementation that has no name -- hence the "anonymous" bit.

This particular bit is what makes your class anonymous:

    InnerClass myInnerClass = new InnerClass() {
        @Override
        void OuterClassMethod() {
            int OuterClassVariable = 10;
            System.out.println("OuterClassVariable" + " " + OuterClassVariable);
        }
    };

In normal class instantiations, you would just use:

InnerClass myInnerClass = new InnerClass();

but in this case, you are specifying a new implementation of that class, by overriding a function (OuterClassMethod()) within it. In other instances of InnerClass, OuterClassMethod() will still have its original implementation, because you only adapted this particular instance of InnerClass, and did not store this new implementation in a new class.

If you don't want anonymous classes, do this instead:

Somewhere, specify AnotherInnerClass to extend InnerClass, and to override that function:

class AnotherInnerClass extends InnerClass {
    @Override
    void OuterClassMethod() {
        int OuterClassVariable = 10;
        System.out.println("OuterClassVariable" + " " + OuterClassVariable);
    }
};

And then instantiate it as such:

AnotherInnerClass myInnerClass = new AnotherInnerClass();

Upvotes: 0

Suyash Singh
Suyash Singh

Reputation: 1

In your example, your class (InnerClass) extends class (OuterClass) and implementing their abstract methods which is the typical behavior of extending an abstract class. In the same way if your class implementing any interfaces you have to override their abstract methods. This is the way to implement Anonymous inner class.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425448

A anonymous class is an "in-line" concrete implementation of a class, typically (but not necessarily) of an abstract class or an interface. It is technically a subclass of the extended/implemented super class.

Google for more.

Upvotes: 1

Related Questions