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.

Similar Messages

  • 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.

  • 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

  • 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.

  • 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

  • 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

  • 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...

  • 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.

  • ER: Override Methods feature should detect anonymous inner class scope

    Hi,
    Given the following code:
    public class Class1 {
        public static void main(String[] args) {
            Thread t = new Thread() {
                // line 4
            t.start();
    }When the cursor is placed on line 4, activating the Override Method dialog (Source menu), should show Thread methods that I can override, in addition to Object methods. Currently only the method from class Object are being shown. The same treatment should also apply to local method inner classes. This happens with the latest 11g preview 3, and all previous versions.

    Hi,
    I'll file an ER
    Frank

  • Anonymous Inner Class oddity

    Anyone feeling alert today ?
    The following code is producing output of:
    Hello
    Fip.run(): nullBut I rather expected to see:
    Hello
    Fip.run(): HelloCan anyone point me to the bit of the JLS that accounts for this ?
    public class TestBuild {
       public static void main(String[] argv) {
          String name = new String("Hello");
          go(name);
       public static void go(final String name) {
          System.out.println(name);
          new Fip() {
             public void run() {
                System.out.println("Fip.run(): " + name);
       private abstract static class Fip {
          public Fip() {
             run();
          abstract void run();
    }Note that the following does produce the expected output, so it's the subtlety of calling the abstract method from the constructor that's escaping me.
    public class TestBuild {
       public static void main(String[] argv) {
          String name = new String("Hello");
          go(name);
       public static void go(final String name) {
          System.out.println(name);
          new Fip() {
             public void run() {
                System.out.println("Fip.run(): " + name);
          }.run(); // <-- Changed !
       private abstract static class Fip {
          public Fip() {
             //run(); // <-- Removed !
          abstract void run();
    }Ouput:
    Hello
    Fip.run(): HelloBoth the above tested in the Sun and Eclipse compilers, with the Sun JVM, so I doubt it's a bug in anything other than my understanding.
    D.

    It seems this thread has not changed and this makes me think that the OP posted bug report and now is waiting for some result. But I am more curious what will be the correct behaviour, how should this be implemented. Let's see what we have:
    1. We have a class (yes, it's anonymous but it is a class) that overrides a run() method in its superclass. This class is TestBuild$1 that extends TestBuild$Fip. We have only class for this anonymous class - I think JLS confitms that too.
    2. In the overrided version of run() we need to use a variable name that can be specified from outside. I say 'variable' because it can differ in different instances of the class that are created in each call to the go(String) method. It must be instance variable since run() accepts no parameters.
    3.I see three ways to pass this variable:
    - Constructor
    - Setter
    - Almost like setter - public(or any other access level that will work) variable
    4.As we know in any of the above ways the instance variable will be initialized after the super() call and thus it will not be set in the call to run() method.
    I am with DrLaszloJamf in reply 3 and think that this case is an example of this statement.
    I would like to see OP's vision of the correct behaviour and the order of things that should happen.
    Thanks for sharing your ideas
    Mike

  • Why i cannot invoke a anonymous inner class's method?

    Why and how to make the 2nd invoke work? thanks!
    import java.lang.reflect.Method;
    public class InvokeTest {
         public static void main(String[] args) throws Exception {
              invoke(new InvokeTest(), "method1"); // this ok
              invoke(new InvokeTest() {/*i want to override some method*/}, "method1"); // this ng: Exception in thread "main"
              // java.lang.NoSuchMethodException: InvokeTest$1.method1()
         void method1() {
              System.out.println("i'm method1");
         private static Object invoke(Object target, String method) throws Exception {
              Class c = target.getClass();
              Method m = c.getDeclaredMethod(method, new Class[] {});
              if (!m.isAccessible()) {
                   m.setAccessible(true);
              Object o = m.invoke(target, new Object[] {});
              return o;
    }this result is:
    i'm method1
    Exception in thread "main" java.lang.NoSuchMethodException: InvokeTest$1.method1()
         at java.lang.Class.getDeclaredMethod(Unknown Source)
         at InvokeTest.invoke(InvokeTest.java:15)
         at ...

    Thanks for your inspiration.
    i changed the code and it worked. share to others
    import java.lang.reflect.Method;
    public class InvokeTest {
         void method1() {
              System.out.println("i'm method1");
         public static void main(String[] args) throws Exception {
              invoke(new InvokeTest(), "method1");
              invoke(new InvokeTest() {
                   void method1() {
                        System.out.println("i'm overrided method1");
              }, "method1");
         private static Object invoke(Object target, String method) throws Exception {
              Class c = target.getClass();
              while (true) {
                   Method m = null;
                   try {
                        m = c.getDeclaredMethod(method, new Class[] {});
                   } catch (Exception e) {
                   if (m == null) {
                        if (c.equals(Object.class)) {
                             break;
                        c = c.getSuperclass();
                        continue;
                   if (!m.isAccessible()) {
                        m.setAccessible(true);
                   Object o = m.invoke(target, new Object[] {});
                   return o;
              return null;
    }result:
    i'm method1
    i'm overrided method1

Maybe you are looking for

  • My network is active but it says it's not when I go to update my iPod. How can I fix this?

    My network connectivity is correct and active but it says it isn't when I go to update my iPod on my PC. It says that the iPod update server cannot be contacted because of this. How can I get my Network to work on my iTunes so I can update my iPod?

  • Ata problems with new dvd drive. [SOLVED]

    I just bought a new dvd-burner. At the first boot I noticed a lot of messages along the lines of: ata2 exception Emask 0x0 SAct 0x0 SErr 0x0 action 0x2 frozen and an extremely long boot time. 3 to 5 minutes. When finally booting in to system the driv

  • Connecting to a HD DVD

    I want to connect my Toshiba HD DVD player to my Airport express so it can update the firmware. My airport express is connected to an airport extreme. How do I do it ? My hd dvd player keeps signaling that it is not connected to the internet. What se

  • IPod Touch 2G electronic discharge when connecting

    Hello, I just wanted to connect my iPod Touch 2G to my PC to put some music on when suddenly i was getting an electrical discharge. I felt the charge coming from the cable trough my finger. This happend before, when i was using a dock. Thought it was

  • Disabling Payment term

    Dear Experts:                         I want to disable payment terms at line item level for customer invoice because i dont want users to change it to save proper aging of overdue invoices. Please tell how will it be disabled at line item level. Reg