When to use anonymous classes?

I am running code containing anonymous classes. I have not met anonymous classes before, so I did some research on them.

My main area of ​​interest is java, so I checked the Oracle tutorial on anonymous classes. I understand the mechanism, and I see that the point is examples, but in my opinion, using anonymous classes makes the code difficult to read and can cause a lot of headache.

Are there cases where it is inevitable to use anonymous classes or is it recommended to use them instead of the named classes?

+4
source share
3 answers

,

, .


, . :

new Thread(new Runnable() {
    @Override
    public void run() {
        // do something
    }
}).start();

Runnable, . , :

private class SomeClass implements Runnable {
    @Override
    public void run() {
        // TODO Auto-generated method stub

    }
}

:

new Thread(new SomeClass()).start();

, , , .


. :

// define some constant which can be used in the anonymous class:
final String someStr = "whatever";

new Thread(new Runnable() {
    @Override
    public void run() {
        // use the String someStr directly
        System.out.println(someStr);
    }
}).start();

, , . , , !

+4

, . . :

void main() {
   new Thread(new Runnable(){
      public void run() {
        System.out.println("Hello world");
      }
   }).start();
}

, .

public class MyRunnable implements Runnable {
   public void run() {
     System.out.println("Hello world");
   }
}


void main() {
   new Thread(new MyRunnable()).start();
}

Java 8 labmda

Runnable task = () -> { System.out.println("hello world"); };
new Thread(task).start();
+4

, ...

. . , , .

?

.

if you implement interfaces that have only one function (e.g. Runnable), then using a lambda expression instead of anonymous classes is not a bad choice.  lamba expression

+2
source

Source: https://habr.com/ru/post/1617971/


All Articles