Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Closure (computer programming)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Local classes and lambda functions (Java) === [[Java (programming language)|Java]] enables [[class (object-oriented programming)|classes]] to be defined inside [[method (object-oriented programming)|methods]]. These are called ''local classes''. When such classes are not named, they are known as ''[[anonymous class]]es'' (or anonymous ''inner'' classes). A local class (either named or anonymous) may refer to names in lexically enclosing classes, or read-only variables (marked as <code>final</code>) in the lexically enclosing method. <syntaxhighlight lang="java"> class CalculationWindow extends JFrame { private volatile int result; // ... public void calculateInSeparateThread(final URI uri) { // The expression "new Runnable() { ... }" is an anonymous class implementing the 'Runnable' interface. new Thread( new Runnable() { void run() { // It can read final local variables: calculate(uri); // It can access private fields of the enclosing class: result = result + 10; } } ).start(); } } </syntaxhighlight> The capturing of <code>final</code> variables enables capturing variables by value. Even if the variable to capture is non-<code>final</code>, it can always be copied to a temporary <code>final</code> variable just before the class. Capturing of variables by reference can be emulated by using a <code>final</code> reference to a mutable container, for example, a one-element array. The local class will not be able to change the value of the container reference, but it will be able to change the contents of the container. With the advent of Java 8's lambda expressions,<ref>{{cite web |url=http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html |title=Lambda Expressions |work=The Java Tutorials}}</ref> the closure causes the above code to be executed as: <syntaxhighlight lang="java"> class CalculationWindow extends JFrame { private volatile int result; // ... public void calculateInSeparateThread(final URI uri) { // The code () -> { /* code */ } is a closure. new Thread(() -> { calculate(uri); result = result + 10; }).start(); } } </syntaxhighlight> Local classes are one of the types of [[inner class]] that are declared within the body of a method. Java also supports inner classes that are declared as ''non-static members'' of an enclosing class.<ref> {{cite web |url=https://blogs.oracle.com/darcy/entry/nested_inner_member_and_top |title=Nested, Inner, Member, and Top-Level Classes |work=Joseph D. Darcy's Oracle Weblog |date=July 2007|archive-url=https://web.archive.org/web/20160831172734/https://blogs.oracle.com/darcy/entry/nested_inner_member_and_top |archive-date=31 August 2016 }}</ref> They are normally referred to just as "inner classes".<ref> {{cite web |url=https://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html |title=Inner Class Example |work=The Java Tutorials: Learning the Java Language: Classes and Objects }}</ref> These are defined in the body of the enclosing class and have full access to instance variables of the enclosing class. Due to their binding to these instance variables, an inner class may only be instantiated with an explicit binding to an instance of the enclosing class using a special syntax.<ref> {{cite web |url=https://java.sun.com/docs/books/tutorial/java/javaOO/nested.html |title=Nested Classes |work=The Java Tutorials: Learning the Java Language: Classes and Objects }}</ref> <syntaxhighlight lang="java"> public class EnclosingClass { /* Define the inner class */ public class InnerClass { public int incrementAndReturnCounter() { return counter++; } } private int counter; { counter = 0; } public int getCounter() { return counter; } public static void main(String[] args) { EnclosingClass enclosingClassInstance = new EnclosingClass(); /* Instantiate the inner class, with binding to the instance */ EnclosingClass.InnerClass innerClassInstance = enclosingClassInstance.new InnerClass(); for (int i = enclosingClassInstance.getCounter(); (i = innerClassInstance.incrementAndReturnCounter()) < 10; /* increment step omitted */) { System.out.println(i); } } } </syntaxhighlight> Upon execution, this will print the integers from 0 to 9. Beware to not confuse this type of class with the nested class, which is declared in the same way with an accompanied usage of the "static" modifier; those have not the desired effect but are instead just classes with no special binding defined in an enclosing class. As of [[Java version history#Java_8|Java 8]], Java supports functions as first class objects. Lambda expressions of this form are considered of type <code>Function<T,U></code> with T being the domain and U the image type. The expression can be called with its <code>.apply(T t)</code> method, but not with a standard method call. <syntaxhighlight lang="java"> public static void main(String[] args) { Function<String, Integer> length = s -> s.length(); System.out.println( length.apply("Hello, world!") ); // Will print 13. } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)