• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
}
}
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic