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("!");
}

Similar Messages

  • 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

  • A question about local inner classes

    Suppose an inner class created in a method:
    public void thisMethod(final int a){
                 class InnerClass {
                   //code
    }Why, in order to use the parameter a in the inner class, I have to pass it final?

    Aurelious wrote:
    JoachimSauer wrote:
    Because you can't refer to the argument of a method once the method call is completed (since the method argument lives on the stack).Why does that matter? If the parameter is of a primitive type, the object will get a copy of it anyway. If the parameter is not primitive, then the value on the stack will be a reference to the argument and not the argument-object itself. In either case, it should then be safe to modify the value after the method returns, as it will either be the primitive copy or a copy of a reference to the object which is itself not on the stack, so the field referenced by the object is still valid either way.
    Am I missing something?If your inner class is using a local variable in the calling method, the expectation is that it's the same variable. But it's not. If it were, then when the stack frame was popped, the variable would be out of scope, which is incompatible with the fact that the inner object can live on.
    On the other hand, if we copy it without making it final, then that's misleading. It looks like I have the same variable, but if I change it in the method, it doesn't change in the object, and vice versa.
    So we have to make a copy to prevent scope/lifetime problems, and we have to make it final so that the copy can be indistinguishable from it being the same variable.

  • 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

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

  • Question about required workshop classes for OCP

    Im working on finishing up my OCP in a few months. Quick question about the workshop class. Is there a test at the end of the week?
    Also how do most people pay for these classes? They are pretty steep and my company doesnt pay for stuff like this for me. Im paying totally out of my own pocket. Also why is the online class the same amount as the instructor lead class? Its not like im in a room at some building that Oracle has to lease for use or something.

    RedDeuce wrote:
    Im working on finishing up my OCP in a few months.What Certificate exactly are you working towards?
    Also how do most people pay for these classes? They are pretty steep and my company doesnt pay for stuff like this for me. Im paying totally out of my own pocket.Then talk to your employer again or maybe look for other jobs that support your plan better.
    Also why is the online class the same amount as the instructor lead class? Its not like im in a room at some building that Oracle has to lease for use or something.They know that you might save on expenses for travel and hotel etc.

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

  • Less dumb follow-up question about super/sub classes in WDJ?

    This is a follow-up question to the question which Maksim answered in this thread:
    Dumb question about super/sub classes in WDJ
    Question:
    Is there any kind of weird C++-like statement that you can put at the top of a WDJ module to force the module to interpret any reference to superclass A as a reference to some specific subclass B of A ???

    David,
    1. Java has no preprocessor, so C++ tricks are not available. Also I would not recommend such tricks even in C++ if you don't want to turn your colleagues working with same code into personal enemies.
    2. The phrase "easier to create a WDJ custom class loader " makes me smile. First, it's not that simple to interfere WDJ class loading scheme. Plus custom class loaders is not trivial Java topic per se.
    3. The problem "replace all A-s with B-s" is typically solved using one or another GoF creation patterns, like <a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern">Abstract Factory</a> or <a href="http://en.wikipedia.org/wiki/Factory_method_pattern">Factory Method</a>. You may use them with custom class loader, if you really want to
    By the way, all UI controls in WD are created using Abstract Factory (role played by view). So you may use this as good example.
    Valery Silaev
    SaM Solutions
    http://www.sam-solutions.net

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

  • Few questions about Calendar / SimpleDateFormat classes

    Hi.
    I have few questions about Calendar class:
    1. How can I get only date representation (without the time)?
    after doing:
    Calendar cal = Calendar.getInstance();
    I tried to clear unecessary fields:
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MINUTE);
    cal.clear(Calendar.HOUR_OF_DAY);
    But after printing the time, it seems that the HOUR was not cleared:
    SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    System.out.println(sdf1.format(cal.getTime()));
    ---> 03/11/2004 17:00:00
    Am I missing somthing?
    2. I want to make sure that two different formats couldn't be compared. i.e., if I'll try to parse one String according to different format -- ParseException will be thrown.
    String date = "19/04/2004 13:06:10";
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date dateObj = sdf.parse(date);
    However, even though that formats are different, no exception is thrown and the return Date is 19/04/2004 00:00:00.
    How can I cause to exception to be thrown if formats are not identical?
    Thanks in advanced

    The Calendar class has a few of what Microsoft would call 'features'. :^)
    To clear the time, call:
    calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY), 0, 0, 0);
    If you want 'pessimistic' rather than 'optimistic' date parsing, you have two options:
    1) Call calendar.setLenient(false);
    See if that is strict enough for your needs, otherwise:
    2) Write code to ensure a stricter parsing of the string passed in. For example, you could very simply check the length of the string to determine if time data is also present.
    When parsing, a string like '02/29/02' would parse to the date '03/01/02'. Setting lenient to false may fix this, but the surest way is to do some testing and then make the parsing more pessimistic where it suits your needs.
    - Saish
    "My karma ran over your dogma." - Anon

  • Question about using container class - Map

    hi all
    i have a question about the following :
    i have two sets of data, both use a common filed as key for the map:
    A = {a,b,d,f,g,h} and B = {a,d,e,g,i,k}, each key has a value associated with.
    i need to find out the commonality, and the difference - i.e fields are in map A but not in Map B, and some fields that are in B but not in A. is there any quick method that comes with the collection class that can calculate this? thanks

    yes, the keyset will be used to access values.
    so, SetA.retainAll(SetB) will modify the SetA so that it contains keys that are in both SetA and SetB - the intersection.
    and SetA.removeAll(SetB) will modify the SetA so that it only contains keys that are in SetA, but not in SetB?
    correct?

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

Maybe you are looking for

  • How to deactivate schedule line in sales order

    hi friends, how can i deactivate the schedule line in sales order so that we can deliver the sales order after the schedule date. i can uderstand that system is not allowing before schedule date. but what if i want to deliver after that. Thanks in ad

  • Using table comparison can we use multiple tables as source?

    Using table comparison can we use multiple tables as source? Thank you very much for the helpful info.

  • Mass change in Assignment Field

    Hi I want to change assignment field for 30 documents together. Let me know if its possible.

  • Need help in kernel upgrade

    Hi, The kernel patch level reverts back to the old kernel when I started SAP after the kernel udate.  This is my first time to upgarde the kernel for win IA64, SAP netweaver04 & Oracle9i. I am used to unix installations. Here are the steps I had made

  • Drag & Drop & Copy and Paste

    Before intalling Leopard I was able to drag jpegs out of safari and onto my desktop or find album artwork and drag it into itunes this feature seems to no longer work. Is there a setting somewhere I can change? Also can no longer copy a URL and paste