Java Lambdas, SAMs And Events
Written by Ian Elliot   
Tuesday, 14 November 2017
Article Index
Java Lambdas, SAMs And Events
Event Handling & Closure
Anonymous Classes

Lambdas Are Anonymous Classes

Before lambdas there were anonymous classes and, the truth of the matter is that lambdas are converted into anonymous classes.  

Anonymous classes where introduced into Java to avoid having to explicitly create a class in a separate file complete with yet another name. It was the best way of implementing event handlers before the lambda was introduced and it is still sometimes the only way to do the job.

It lets you effectively create an object, i.e. an instance of a class, without having to explicitly create a class, so providing a direct method of creating the event object.

Instead of:

Event Class implementing the interface -> Event Object
        -> Set As Listener

we just go straight to:

Event Object -> Set As Listener

The only downside of using anonymous classes is that you can't create a second instance of the class. It works only as a shortcut way of creating one instance of an object.

You create an anonymous class by writing the same code you would need to create an instance of an existing class, but you add

{block of code}

following it to define the new methods of the new class you are creating. The result is an instance of the new class.

For example suppose you have a class called Hello that displays a hello world message and you want an object that does everything that Hello does but with the addition of a goodbye method. Normally you would create a Leave class that inherits from Hello and defines the new method and then create an instance of Leave. Instead you can write:

Hello leave = new Hello(){
  goodbye(){
       display message;
  }
}

This create an instance of Hello that has all of the Hello methods plus the new goodbye method. Notice that leave is an object and not a class and you can call methods such as leave.goodbye() at once.

You have avoided having to create a new class just to create one instance of it. If the class you are extending has a constructor that needs parameters, simply call the constructor in the usual way and add the code that extends the class immediately after. 

So going back to our very first example of a SAM we have:

public interface Sum{
        int sum(int a, int b);
}

and we can immediately create an instance of this interface with an implementation of the sum method using:

Sum adder = new Sum() {
            @Override
            public int sum(int a, int b) {
                return a+b;
            }
          };

And after this we can use the function as before:

int ans=adder.sum(1,2);

But wait!

This is what the lambda function produced. 

This is always the case and there is a direct connection between a lambda function and an anonymous class implementation of a SAM. 

That is:

Sum adder = (a,b)->{
                    return a+b;

             };

is almost exactly equivalent to:

Sum adder = new Sum() {
             @Override
             public int sum(int a, int b) { 
               return a+b;
             } 
          };

Why "almost exactly"?

The answer is that while an anonymous class support closure in the same way as the lambda it introduces a new scope. Put simply you can create new variables within an anonymous class that shadow variables in the enclosing method but you can't in a lambda. This is usually only a problem when you are converting an anonymous class to a lambda.

"Use the lambda Luke" - when you can, that is.

 lambdaicon

Related Articles

Lambda Calculus For Programmers

Lambda Expressions

Javascript Jems - Lambda expressions

Deep C# - Anonymous Methods, Lambdas And Closures

What Exactly Is A First Class Function - And Why You Should Care 

Lambdas and Delegates - Why Bother?

Modern Java
With NetBeans And Swing

largecover

Contents

  1. Why Java?
  2. Getting started with Java
  3. Introducing Java - Swing Objects
  4. Writing Code
  5. Command Line Programs
  6. User Interface - More Swing
  7. Working With Class
  8. Java Class Inheritance
  9. Java Data Types - Numeric Data
  10. Java Data Types - Arrays And Strings
  11. Building a Java GUI - Containers
  12. Advanced OOP - Type, Casting, Packages
  13. Value And Reference 
  14. Java Lambdas, SAMs And Events

 

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

raspberry pi books

 

Comments




or email your comment to: comments@i-programmer.info

<ASIN:0072263849>

<ASIN:0072263148>

<ASIN:0132354764>

<ASIN:1849511764>

<ASIN:0321356683>



Last Updated ( Tuesday, 14 November 2017 )