Anonymous Inner Class question

How can I get "foof" to be echoed to the screen?
class MyClass {
   void go() {
      Bar b = new Bar();
      b.doStuff(new Foo() {
         public void foof() {
            System.out.println("foof");
interface Foo {
   void foof();
class Bar {
   void doStuff(Foo f) {}
public class TestWonder {
   public static void main (String... args) {
   new MyClass().go();
   //Why doesn't this print out "foof" to the screen? Nothing is echoed to the screen.
}

Sorry to be so thick, but I thought that the code did that already. Apparently it doesn't. In other words, how would the code invoke the override foof()? I should be clearer:
I know if I change Bar's doStuff() to
void doStuff(Foo f) {
System.out.println("bar's dostuff");
}then when go() is executed bar's dostuff will print out. But, what about the override in the anonymous inner class?
Edited by: RonNYC2 on Feb 5, 2010 1:03 PM
Edited by: RonNYC2 on Feb 5, 2010 1:05 PM

Similar Messages

  • Question about anonymous inner class??

    Is there any error occurs,If a class declear & implement two anonymous inner classes ??

    public class TryItAndSee {
        void m() {
            Runnable x = new Runnable(){
                public void run() {
                    System.out.println("?");
            Runnable y = new Runnable(){
                public void run() {
                    System.out.println("!");
    }

  • Question on Anonymous Inner class !

    Can an Anonymous Inner class implement or extend any thing?
    I feel no .. if yes can anyone give an example please..

    An example: the anonymous inner class in u extends Thread.
    $ cat u.java
    class u {
    public static void main(String a[]) {
    Thread t = new Thread ( ) {
    public void run() {
    System.out.println(getClass().getName());
    t.start();
    $ javac u.java
    $ java u
    u$1
    $
    The same idea but with the Runnable interface (and not class)
    $ cat u.java
    class u {
    public static void main(String a[]) {
    Thread t = new Thread ( new Runnable ( ) {
    public void run() {
    System.out.println(getClass().getName());
    t.start();
    $ java u
    u$1

  • Trying to use super class's methods from an anonymous inner class

    Hi all,
    I have one class with some methods, and a second class which inherits from the first. The second class contains a method which starts up a thread, which is an anonymous inner class. Inside this inner class, I want to call a method from my first class. How can I do this?
    If I just call the method, it will use the second class's version of the method. However, if I use "super," it will try to find that method in the Thread class (it's own super class) and complain.
    Any suggestions?
    Code:
    public class TopClass
         public void doSomething(){
              // do something
    =============================
    public class LowerClass extends TopClass
         // overrides TopClass's doSomething.
         public void doSomething(){
              // do something
         public void testThread(){
              Thread t = new Thread(){
                   public void run(){
                        doSomething();               //fine
                        super.doSomething();          //WRONG: searches class Thread for doSomething...
              t.start();
    }

    Classes frequently call the un-overridden versions of methods from their superclasses. That's that the super keyword is for, if I'm not mistaken.You're not mistaken about the keyword, but you're not calling the superclass method from a subclass. Your anonymous inner class is not a subtype of TopLevel. It's a subtype of Thread.
    Here it is no different, except that I happen to be in a thread at the time.It's vastly different, since you're attempting to call the method from an unrelated class; i.e., Thread.
    I could also be in a button's action listener, for example. It seems natural to me that if I can do it in a method, I should be able to do it within an anonymous inner class which is inside a method.If you were in an button's action listener and needed to call a superclass' implementation of a method overridden in the button, I'd have the same questions about your design. It seems smelly to me.
    ~

  • Semi-Anonymous Inner Class?

    From API description of invokeLater method of SwingUtilities class:
    /* begin quote
    In the following example the invokeLater call queues the Runnable object doHelloWorld on the event dispatching thread and then prints a message.
    Runnable doHelloWorld = new Runnable() {
    public void run() {
    System.out.println("Hello World on " + Thread.currentThread());
    SwingUtilities.invokeLater(doHelloWorld);
    System.out.println("This might well be displayed before the other message.");
    */ end quote
    The interface class is named (doHelloWorld) so it's not really anonymous.
    But the class is not declared; there's no class keyword.
    Is there a formal name for this construction?
    It seems like a hybrid of named and anonymous implementation.
    I guess the ability to mix class declaration, instantiation, method declaration, etc in one statement is powerful but just hard for beginner to understand when to use.
    Sigh, three ways to do same thing. This 'hybrid' form is actually harder to understand than other ways.
    private class myRunnable implements Runnable {
    public void run() {
    System.out.println("Hello World on " + Thread.currentThread());
    myRunnable doHelloWorld = new myRunnable();
    OR
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    System.out.println("Hello World on " + Thread.currentThread());
    Thanks,
    Stanley.

    The interface class is named (doHelloWorld) so it's
    not really anonymous. No. There's a variable that points to an instance of that class, and the variable is named doHelloWorld. The class is anonymous.
    Is there a formal name for this construction?Anonymous inner class.

  • Adapters vs anonymous inner class (please help)

    I am trying to clean up my code by using anonymous inner classes to handle some action events. My code looks like this but I get an error
    Button.addActionListener(new MyClass() {
    public void actionPerformed(ActionEvent e) {
    my_Button_actionPerformed(e);
    it says that it cant find MyClass, but I thought I dont need to define it becaue I am defining it here, isnt that the point of a anonymous inner class

    yourBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
    });(BTW: use code tags in posting!)

  • Mysterious anonymous inner class in switch block

    public class MysteryFile {
      public enum Elements {
        WIND, EARTH, FIRE, WATER
      Elements el;
      public MysteryFile(Elements el) {
        this.el = el;
      public void whatIsItLike() {
        switch (el) {
          case WIND: System.out.println("A bit chilly sometimes"); break;
          case EARTH: System.out.println("Gets hands dirty."); break;
          case FIRE: System.out.println("Hot! skin melt"); break;
          case WATER: System.out.println("Cool! clean hands"); break;
          default: System.out.println("Don't know"); break;
      public static void main(String[] args) {
        MysteryFile anElement = new MysteryFile(Elements.FIRE);
        anElement.whatIsItLike();
    }When compiled in Netbeans or in the command line, generates an unexpected MysteryFile$1.class file. If the entire switch block is commented out and recompiled, it does not get generated. Where does this anonymous inner class come from?

    The MysteryFile$1 class looks something like this (javac 1.6.0_02):
    class MysteryFile$1 {
      static final int[] $SwitchMap$MysteryFile$Elements;
      static {
          // the line number (debug info) of this static initializer
          // is "switch (el)" line in MysteryFile.java
          $SwitchMap$MysteryFile$Elements =
                  new int[MysteryFile$Elements.values().length ];
          try {
              $SwitchMap$MysteryFile$Elements[
                      MysteryFile$Elements.WIND.ordinal() ] = 1;
          } catch (NoSuchFieldError e) {
              // fix stack?
          // repeat with EARTH(2), FIRE(3) and WATER(4)
    }... and the actual switch statement in 'MysteryFile' looks like so:
      //switch (el) {
      switch(MysteryFile$1.$SwitchMap$MysteryFile$Elements[
              this.el.ordinal() ])
      case 1:  // WIND
          break;
      case 2:  // EARTH
          break;
      case 3:  // FIRE
          break;
      case 4:  // WATER
          break;
      default:  // ...
      }I suppose this is necessary because the compiler can't guarantee that the runtime enum-constant-to-ordinal mapping will be identical to that at compile time (the API docs say it depends on the declaration order in the source code, which I think may change without breaking binary compatibility).
    PS MysteryFile$Elements.values() is a synthetic method that returns all enumeration constants in a MysteryFile$Elements array. Found this old related thread: [http://forum.java.sun.com/thread.jspa?threadID=617315]

  • Cant complie "anonymous inner class" on JDK1.4

    public Enumeration enumerator()
    return new Enumeration()
    int currentItem = items.size() - 1;
    public boolean hasMoreElements() {
    return (currentItem >= 0);
    error: cant resolve symbol
    help me! thanx u very much

    Since Enumeration is an interface, the anonymous inner class needs to implement both functions.
    public Enumeration enumerator()
      return new Enumeration()
         int currentItem = items.size() - 1;
         public boolean hasMoreElements()
            return (currentItem >= 0);
         public Object nextElement()
            return items.elementAt(currentItem--);
    }I assume that items is a member field of the class containing this method. Since I don't know what it is , the elementAt is only a guess.

  • Annoyomous Inner class question

    Is the test instance simply an instance of an annoyomous class which extends the MyClass class and provides a different implementation of it's printStuff() method?
    I want to make sure I understand why annoyomous class can be useful.
    Thanks ...
    class Tester {
       MyClass test = new MyClass(){
            protected void printStuff(){
                 System.out.println("Annoyomous class");
    class MyClass {
       protected void printStuff(){
         System.out.println("Original class");
    }

    I've read 2 chapters from different books on Anonymous Inner classes but I need to be sure I've grasped the concepts in my own head.
    I have replaced
    class Tester {
       MyClass test = new MyClass(){
            protected void printStuff(){
                 System.out.println("Annoyomous class");
    }With
    class Tester {
       MyClass test = new MyNewClass();
    class MyNewClass extends MyClass {
       protected void printStuff(){
            System.out.println("Annoyomous class");
    }This works the same way so
    Is the latter a more compact way to do one off extension and instaniation of a class.
    Would the latter be a better solution if you need to create more than one instance of the same anonymous class?

  • Anonymous inner class

    Hello
    In the following piece of code:
    import static tools.Print.*;
    interface ForInner {
         void who();
         String toString();
    class ForInnerWithParameters {
         int i;
         String s;
         ForInnerWithParameters(int i) {
              this.i = i;
    class NackedClass {
         public ForInner inner() {
              return new ForInner() {
                   private int i;
                        print("Inside inner class!");
                        i = 10;
                   public int getI() {
                        return i;
                   public void who() {
                        print("It's me, inner!");
                   public String toString() {
                        return "Anonymous class";
         public ForInnerWithParameters innerWith(int i, final String s) {
              return new ForInnerWithParameters(i) {
                   {     print("i = "+i);
                        print(s);
                        super.s = s;
                   public String getS() {
                        return s;
         public static void main(String[] args) {
              NackedClass nc = new NackedClass();
              ForInner fi = nc.inner();
              fi.who();
              ForInnerWithParameters fiwp = nc.innerWith(91, "Hello");
              print(fiwp.i);
              print(fiwp.s);
    i would like to assign to the variable s (inside ForInnerWithParameters class) the value "Hello" passed as a parameter in the main ( ForInnerWithParameters fiwp = nc.innerWith(91, "Hello"); )
    The method innerWith(int i, final String s) is getting the values 91 and "Hello". Both, the parameter in the method and the parameter in the class are named s. How can I assign the value s ("Hello") to the parameter s inside the class? this.s = s or super.s = s doesn't work. The only solution I found is to change either the name of the parameter s inside the method or the name of the parameter s inside the class.
    I hope the question is clear enough!
    Thanks a lot!

    I would have expected this.s to work, providing you used it every time (including getS()).
    But, to be honest, why bother? It's just pointlessly confusing to use s as your method parameter.

  • Inner Class Question

    My question pertains to the code at the bottom of this post.
    I don't understand why the compiler doesn't give an error for the line below. Why would it let you refer to something inside the class (in this case I'm referring to ClassWithInnerClass.MyInnerClass) unless it were static?
    ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();To illustrate why I'm asking, I created 2 ints ("regularInt" and "staticInt") inside class "ClassWithInnerClass". The compiler let me set the value of "staticInt" from within main whereas it wouldn't let me do so w/ "regularInt" (which is why I commented that line out). Don't get me wrong though - I understand the reasons why the compiler behaves as it does for "regularInt" and "staticInt". I understand that a static variable can be accessed without instantiating a class (and that there's only 1 created no matter how many classes are instantiated). I also understand that, to access a non-static variable, you need to instantiate a class. My question arises only because of trying to extend that logic to MyInnerClass.
    I can already take a guess that the answer is going to be something like, "the reason it works this way is because class 'MyInnerClass' is just a declaration NOT a definiton". I guess I just want confirmation of this and, if possible, some reasoning behind this logic.
    HERE'S THE CODE...
    class CreateInnerClasses {
         public static void main (String args[]) {
              ClassWithInnerClass cwic = new ClassWithInnerClass();
              ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();
              //ClassWithInnerClass.regularInt = 5;
              ClassWithInnerClass.staticInt = 10;
              mic.printIt();
    class ClassWithInnerClass {
         public int regularInt ;
         static public int staticInt;
         class MyInnerClass {
              void printIt() {
                   System.out.println("Inside ClassWithInnerClass.myInnerClass");
         MyInnerClass retMyInnerClass () {
              return new MyInnerClass();

    The line    ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();is accepted because the name of the inner class is ClassWithInnerClass.MyInnerClass. This has nothing to do with accessing fields even though the syntax is similar.
    On the other hand, the line    SomeClassWithAnInnerClass.InnerClass ic = new SomeClassWithAnInnerClass.InnerClass();is not accepted because the nested class SomeClassWithAnInnerClass.InnerClass is not static: you must have an instance of the outer class available. The correct syntax for calling the constructor of the inner class would be    Outer.Inner instance = outerInstance.new Inner();In this case you could write:    ClassWithInnerClass.MyInnerClass mic =  new SomeClassWithAnInnerClass() . new InnerClass();
        // OR:
        ClassWithInnerClass.MyInnerClass mic =  cwic . new InnerClass();The Java tutorial has a pretty good explanation on nested classes:
    http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
    http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html

  • Accessing member variable within an anonymous inner class

    I'm getting a compiler error with the following snippet which resides in a constructor (error below):
            final String fullNamesArr[] = new String[ lafsArr.length ];
            String lafNamesArr[] = new String[ lafsArr.length ];
            JMenuItem namesMenuItemArr[] = new JMenuItem[ lafsArr.length ];
            for ( int i = 0 ; i < lafsArr.length ; i++ )
                StringTokenizer tokenizer;
                fullNamesArr[ i ] = lafsArr[ i ].getClassName();
                tokenizer = new StringTokenizer( fullNamesArr[ i ] );
                while ( tokenizer.hasMoreTokens() )
                    lafNamesArr[ i ] = tokenizer.nextToken( "." );
                namesMenuItemArr[ i ] = new JMenuItem( lafNamesArr[ i ] );
                lafMenu.add( namesMenuItemArr[ i ] );
                namesMenuItemArr[ i ].addActionListener(new ActionListener()
                        public final void actionPerformed(final ActionEvent e)
                            String actionCommand = e.getActionCommand();
                            int iCount = 0;
                            for ( int index = 0 ; index < fullNamesArr.length ; index++ )
                                if ( fullNamesArr[ index ].contains( actionCommand ))
                                    iCount = index;
                                    break;
                            System.out.println( "Setting LAF to '" +
                                                fullNamesArr[ iCount ] + "'" );
                            try
                                UIManager.setLookAndFeel( fullNamesArr[ iCount ] );
                            catch ( UnsupportedLookAndFeelException ulafe )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Not a valid LAF class." );
                            catch ( ClassNotFoundException cnfe )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Class not found." );
                            catch ( InstantiationException ie )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Can't instantiate class." );
                            catch ( IllegalAccessException iae )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Illegal access." );
    DBBuilder.java:1280: cannot resolve symbol
    symbol : method contains (java.lang.String)
    location: class java.lang.String
    if ( fullNamesArr[ index ].contains( actionCommand ))
    ^
    1 error
    BUILD FAILED
    My question: Why can I access fullNamesArr in other spots in the anon-inner class,but not with the String.contains() method? BTW, the carrot is under the left bracket '['.
    TIA,
    Jeff

    My question: Why can I access fullNamesArr in other
    spots in the anon-inner class,but not with the
    String.contains() method? BTW, the carrot is under
    the left bracket '['.You're misinterpreting the message. The problem is not your variable fullNamesArr, but rather the method contains(java.lang.String). Since that method was only added in Java 5 (aka 1.5) you might look if you're compiling with JDK 1.4 or earlier.

  • BUG: Oracle Java Compiler bug with anonymous inner classes in constructor

    The following code compiles and runs just fine using 1.4.2_07, 1.5.0_07 and 1.6.0_beta2 when compiling and running from the command-line.
    It does not run when compiling from JDeveloper 10.1.3.36.73 (which uses the ojc.jar).
    When compiled from JDeveloper, the JRE (both the embedded one or the external 1.5.0_07 one) reports the following error:
    java.lang.VerifyError: (class: com/ids/arithmeticexpr/Scanner, method: <init> signature: (Ljava/io/Reader;)V) Expecting to find object/array on
    stack
    Here's the code:
    /** lexical analyzer for arithmetic expressions.
    Fixes the lookahead problem for TT_EOL.
    public class Scanner extends StreamTokenizer
    /** kludge: pushes an anonymous Reader which inserts
    a space after each newline.
    public Scanner( Reader r )
    super( new FilterReader( new BufferedReader( r ) )
    protected boolean addSpace; // kludge to add space after \n
    public int read() throws IOException
    int ch = addSpace ? ' ' : in.read();
    addSpace = ch == '\n';
    return ch;
    public static void main( String[] args )
    Scanner scanner = new Scanner( new StringReader("1+2") ); // !!!
    Removing the (implicit) reference to 'this' in the call to super() by passing an instance of a static inner class 'Kludge' instead of the anonymous subclass of FilterReader fixes the error. The code will then run even when compiled with ojc. There seems to be a bug in ojc concerning references to the partially constructed object (a bug which which is not present in the reference compilers.)
    -- Sebastian

    Thanks Sebastian, I filed a bug for OJC, and I'll look at the Javac bug. Either way, OJC should either give an error or create correct code.
    Keimpe Bronkhorst
    JDev Team

  • Inner classes question

    Hi guys,
    I have a question to ask - when i'm writing an inner class and i want to create a new instance from it, the Eclipse forces me to use an instance of the containing class to call new.
    Is it how it's done or am i doing something wrong?
    public class A
        // Some code here
        public class B
             //Some code here
    }Trying to create an instance:
    A a = new A();
    A.B b = a.new B();

    What you have defined is "non-static" inner class.A "non-static" can only be instantiated only if we create an object of outer class.True.
    >
    There are two ways to create "inner" class object,
    1)The way you have written the codeTrue.
    2)
        public class A
    {    // Some code here    
    public void createInner()
    classB b=new ClassB();
    public classB   
    //Some code here   
    That code won't compile. Even if you corrected it so that it did compile, it doesn't really help in the OP's situation. Did you read the advice of Saish and Jos about why class 'B' probably shouldn't be public, anyway?

  • Pass an array of argument defined anonymous inner class

    Can someone plz tell me what is wrong with this code?How can I correct it?
    interface NotImplemented{
         public void disp();
    public class Anonymous{
         public void disp(NotImplemented[] ni){
              System.out.println(ni.length);
              ni[0].disp();
         public static void main(String args[]){
              Anonymous a=new Anonymous();
              a.disp(new NotImplemented[5]{
                   public void disp(){
                        System.out.println("Array of inner classes disp");
    }     

    This is what I wanted to do:
    interface NotImplemented{
         public void disp();
    public class Anonymous{
         public void disp(NotImplemented[] ni){
              System.out.println(ni.length);
              ni[0].disp();
              ni[1].disp();
         public static void main(String args[]){
              Anonymous a=new Anonymous();
              a.disp(new NotImplemented[]{
                        new NotImplemented(){
                             public void disp(){
                                  System.out.println("Inside first implementor of NotImplemented interface");
                        new NotImplemented(){
                             public void disp(){
                                  System.out.println("Inside second implementor of NotImplemented interface");
    Thanks for all your help...

Maybe you are looking for

  • Time Zone issues

    Hi Everyone! Today something really strange happened with the time in my MacBook Pro. It changed automatically. I check the Day & Time settings and I realize that my automatically set time zone is in Paradise, NV, when currently I'm living in the nor

  • No image appearing in 'New tab' tiles

    no image appearing in new tab tiles that thumbnails are not displayed in the tiles.how to solve this?

  • Help , recurring pages upon hitting a tab in many websites

    For months (at least 2)when I go on MANY site and then hit a tab in that site ,it opens multiple pages till I shut my computor down with force quit...also the spin wheel thing is showing up now all the time and the computor has become slow last coupl

  • Screen sharing is hit or miss

    Ever since replacing my 2007 iMac with a new Mac Mini in Dec. 2012, the ability to share the Mini's screen from my 2011 MBP is a hit or miss, same goes for rmounting the disk in the Mini.  I cannot recall this ever happening with the iMac. I usually

  • Third party prod in R3 system needed?

    Hi Friends, I have to do Communication between R/3 and Third party Legacy system. I will create the technical system for R/3 by executing RZ70 transaction which will create Technical system in SLD of XI. While creating the Third party system first I