1

I read that Java 8 supports Closures, but I just wanted to know that as any function inside a class can access a global variable, so how can Java previously didn't support Closures ?? See below example.

public class HelloWorld{
  int number = 5;
  public void fun() {
    System.out.println("number: " + number); // Here fun() can access number.
  }
  public static void main(String []args){
    System.out.println("Hello World");

    new HelloWorld().fun();
  }
}

I think there is something about Closures which I didn't get ??

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
Sudhanshu Gaur
  • 7,486
  • 9
  • 47
  • 94
  • I think you're confusing scope with closure, closures in java were done by using inner classes which is pretty awful and verbose. – calbertts May 19 '18 at 11:54

1 Answers1

0

The only thing that could be thought of as a closure prior to JDK-8 is inner classes.

So what is a closure?

A closure is pretty much like a lambda, except they reference variables outside the scope of the function. in other words, a closure is some type of behaviour which you can pass around and it references variables outside of its scope.

What Java-8 has done is provide closures with a more attractive syntax than inner classes.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126