Question

I am learning java swing and came across the concept of anonymous inner class. After studying a bit at this link, I feel that an anonymous inner class must always extend some other class since the method in which it gets passed as a parameter is predefined. At most, if a method accepts Object instances as parameter, only then we can create an anonymous independent inner class. I just seek your opinion whether I am right. It would be helpful if you could provide some example. Thanks in advance.

Was it helpful?

Solution

Creating an anonymous inner class without extending anything would basically mean that you'd have no way of talking to it.

You need to extend a class or implement an interface just to give your object known methods to talk to, for example;

myButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
        // do something here.
    }
});

The only way to talk to an instance of that object is through the known ActionListener methods (which happens to be exactly the methods addActionListener needs), any other methods you'd add would only be accessible inside the object itself. If you didn't have to extend/implement anything, no methods would be externally accessible at all.

OTHER TIPS

Every class must extend some superclass. The only exception is java.lang.Object, which is the top-level class and thus can't have a superclass. Anonymous inner classes are no different in this regard.

The purpose of inner classes is to "package" implementations of an operation in a way that you can use from other places. This lets you implement a concept of callbacks, when you pass a piece of code to a method that can pass the control back to you.

The base class/interface is there to provide an access point to that piece of code. You and the method that you call agree on the name and the signature of the callback method by agreeing on the interface that your inner class (actually, any class) must implement for the target method to be able to call you back.

To be more specific, in order for the window to call back your window listener, you must agree on the name and the signature of the windowClosing method. You do it by implementing an interface.

In rare cases when the target method is one implemented by java.lang.Object (e.g. toString) you can derive your named or anonymous inner class from the top-level Object.

you are right with your statement i.e. class through which you make anonymous inner class inherit that class automatically as in this case anonymous class inherit class C

 class C
{
void one()
{
System.out.println("***************************\n********");

}
}
class three
{
public static void main(String args[])

{
C obj=new C(){
             void one()
             {
             System.out.println("//////////////");
              }
           };
 obj.one();

}

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top