Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Anonymous inner class ....

 
Shrini Kulkarni
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,
Look at this piece of code :
class superclass
{
superclass()
{
};
void aMethod()
{
}
}
public class ee
{
//following commented method does not compile
// gives error : type expected on the line .. new superclass ..
/*
public void useAnonymousInnerclass(
new superclass()
{
public SomeMethod()
{
System.out.println ("anonymous inner class ");
}
}
);
*/

// where as this method compiles..
public superclass AnotherWayOfUsingAnoInnerClass()
{
return new superclass()
{
int ii =0;
};
}
}
Any clues as why this is happening ?
Shrinivas
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
In your first method (the one that won't compile) you are trying to accept an anonymous class as an input parameter to a method. If the class is anonymous how on earth will you ever be able to call the method?
In your second method you are correctly returning an anonymous class so the caller can then make use of it.
Regards,
Manfred.
 
Shrini Kulkarni
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK got the point :
We can use the anonyumous classes in a method call where an object reference is expected Not while declaring method itself.
Quote from KAM :
"An anonymous class can be used where a reference can be used"
Thanks for clarification
Shrinivas
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic