Actually I wanted the Dog class to be the anonymous inner class,
Just a nitpick, but you want some *subclass* of' Dog to be an anonymous class. I just want to emphasise the point that anonymous classes have no name, so you can never (reasonably) say "I want Whatever to be an anonymous class".
---
ActionListener is a good - and typical - example. Which answers your question about "what's the point of using anonymous inner classes". They are used when they implement some behaviour described in the parent and where it makes sense to put the implementation close to some other object. (the way the listener implementation is close to the button instantiation.)
In fact you *can* call the actionPerformed() method if you really want to. All that's needed is that you have a variable with which to call it:
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// stuff happens here
}
} // listener is an instance of an anonymous subclass of ActionListener
button.addActionListener(listener);
// the following is quite "legal"
listener.actionPerformed(null);
Of course null is not a "proper" argument, but so long as nothing depends on getting a "real" ActionEvent there will be no problems. In any event it compiles OK, so methods of anonymous subclasses can be called.
Note that actionPerformed() is declared in the (non-anonymous) ActionListener class. The problem arises only when you want to call some method that is *not* declared in the nonanonymous parent. The compiler - as always - insists that the variable (or other expression) has a type where this new method is declared. But you can't declare such a variable because the class in question has no name. And you can't cast an expression of the parent type to the anonymous subtype either, for the same reason.
The bottom line is that if you want a class which declares some method you intend calling later you had better give that class a name:
// untested - access modifiers removed since the example involves a *local* class
public void zing()
{
final String hero = "Snoopy";
class DogEx extends Dog
{
DogEx(String name)
{
super(name)
}
void new_dog_method()
{
System.out.println(hero);
System.out.println("ABC");
System.out.println("123 and so forth");
}
};
DogEx d = new DogEx("Ash Ketchum");
d.new_dog_method();
System.out.println("output inside zing method but outside anonymous inner class");
}
You ought to have a reason for complexifying the code in this way. Ie some reason not to define DogEx in its own file.