Search code examples
javaanonymous-class

Is it possible to call several methods from an anonymous class?


I want to know if its possible this in some way pls java 7 or 8

public class App{
    public static void main(String[] args) {
        new Thread(){
            public void run(){
                //Something
            }
        }.start().setName("Something") //Here!!
        //Something
    }
}

Solution

  • No, this is not possible since neither start() nor setName() returns the thread. The created anonymous class, is a subclass of Thread, so it can be assigned to such a variable:

    Thread thread = new Thread {
        // something
    };
    thread.setName(...);
    thread.setPriority(...);
    thread.start();
    

    or using functional notation:

    Thread thread = new Thread( () -> { ... } );
    thread.setName(...);
    thread.setPriority(...);
    thread.start();
    

    and my preferred (no additional class being created), using method reference:

        Thread thread = new Thread(this::runInThread);
        thread.setName(...);
        thread.setPriority(...);
        thread.start();
        ...
    }
    
    private void runInThread() {
        // something to run in thread
    }
    

    added setPriority() just to have more calls