SE450: Inner Class: Lambda [7/16] Previous pageContentsNext page

Unnamed inner classes that just have a single function can use a shorthand.

file:Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package basics.inner.five;
public class Main {
  private Main() {}
  static public void main (final String[] args) {
    C mc1 = new C(42);
    C mc2 = new C(36);
    mc1.f();
    mc2.f();
  }
}

interface Print { void print(); }

class C {
  int cx;
  C(int x) { cx = x; }
  void f() {
    Print p = () -> System.out.println(" cx=" + cx);
    p.print();
    
    G g = (int x) -> {
      cx = cx + x;
      cx = cx + x;
      cx = cx + x;
    };
    g.run(3);
  }
}

interface G { void run(int x); }

Previous pageContentsNext page