The beauty of anonymous inner classes lies in the fact that, that there are so many UNUSUAL/WEIRD ways to define them,

1. Anonymous inner classes, can be defined within a method.(This is similar to method local inner classes)

2.They can also be defined within “AN ARGUMENT TO A METHOD”.

3. Within any class but with no name.

Eg.

class Popcorn

{

public void pop(){System.out.println(“Popcorn”);}

}

class Food

{

Popcorn p=new Popcorn(){

public void pop(){System.out.println();}

};                              <–Please notice the closing semicolon.

}

Now, match this, Food has absolutely no methods of its own(wats pop doing then??),  The popcorn reference variable P will “NOT” refer to an instance of popcorn but to an instance of a subclass of popcorn, which happens to be ANONYMOUS.

Argument local inner classes:

Lets say we have an interface Foo,

interface Foo{

void foof();

}

and i have a class Bar,

class Bar

{

void doStuff(Foo f){}

}

and a class called wonderful which needs to pass a foo implementer object to dostuff of Bar,

This will be done as,

Bar b=new Bar();

b.doStuff(new Foo(){

public void foof(){System.out.println(“foofy”);}

});//This is a classic example of argument local inner classes

Difference between instance creation of static nested class and normal inner class,from outside:

For a static nested class located inside the class BigOuter,

BigOuter.Nest bn=new BigOuter.Nest();

For a normal inner classs

MyOuter.MyInner inner=new MyOuter().new MyInner();

Advertisements