• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is there a way to invoke new methods defined in Anonymous classes?  RSS feed

 
Dinuka Arsakularatne
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in the following code is there anyway i can call the new method called sizzle and get it to run? if it is not possible then could i please know the use of using anonymous classes?

class Popcorn {
public void pop(){
System.out.println("pop corn");
}
}

class Food {
Popcorn p = new Popcorn(){
public void pop(){
System.out.println("anonymous popcorn");
}
public void sizzle(){
System.out.println("fdsaf");
}
};
public static void main(String ar[]){
Popcorn p = new Popcorn();
p.pop();
p.sizzle();// does not compile. is there a way to get it to work?
}
}
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There might be a way using reflection, but that's probably a bad idea.

Simply don't use anonymous inner classes if you need to add methods, use them only to implement or override methods declared in the superclass/interface.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!