Sunday, 24 November 2013

Accessing Local and instance variable in Java 8 using Lambda .

The following code helps us understand the concept of accessing local and instance variables in java 8.
In the following code , "wildAnimal" is the instance variable and "domesticAnimal"  is the local variable declared in the program.The thread constructor is overrided to start the thread using the -> expression .

package com;
public class LambdaVariableAccess {
  public String wildAnimal = "Lion";

  public static void main(String[] arg) {
    new LambdaVariableAccess().lambdaExpression();
  }
public void lambdaExpression(){
        String domesticAnimal = "Dog";
        
        new Thread (() -> {
            System.out.println("Class Level: " + this.wildAnimal);
          System.out.println("Method Level: " + domesticAnimal);
       }).start();       
    }
}

No comments:

Post a Comment