- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are the scoping rules for lambda expressions in Java?
There are different scoping rules for lambda expression in Java. In lambda expressions, this and super keywords are lexically scoped means that this keyword refers to the object of the enclosing type and the super keyword refers to the enclosing superclass. In the case of an anonymous class, they are relative to the anonymous class itself. Similarly, local variables declared in lambda expression conflicts with variables declared in the enclosing class. In the case of an anonymous class, they are allowed to shadow variables in the enclosing class.
Example
@FunctionalInterface interface TestInterface { int calculate(int x, int y); } class Test { public void showValue(String str) { System.out.println("The value is: " + str); } } public class LambdaExpressionTest extends Test { public static void main(String[] args) { LambdaExpressionTest lambdaObj = new LambdaExpressionTest(); lambdaObj.getResult(); } public void getResult() { TestInterface ref = (x, y) -> { // lambda expression System.out.println("The toString: " + this.toString()); super.showValue("Calling from Lambda"); return x*y; }; System.out.println("Result is: " + ref.calculate(8, 6)); } }
Output
The toString: LambdaExpressionTest6@87aac27 The value is: Calling from Lambda Result is: 48
Advertisements