Institute of Computer Science
  1. Courses
  2. 2017/18 spring
  3. Object-Oriented Programming (Narva College) (P2NC.01.083)
ET
Log in

Object-Oriented Programming (Narva College) 2017/18 spring

  • Home
  • Materials
  • Java Glossary
  • Source Example
  • Cheat sheet (S1-S6)
  • Grading
  • Links
Session 9

Simplifying event handling using lambda expressions

Lambda expressions can be used to greatly simplify coding for the event handling. The lambda expression is a new feature in Java 8. Lambda expressions can be viewed as an anonymous class with a concise syntax. For example, the following code on the left can be greatly simplified using a lambda expression on the right in three lines.

The basic syntax for a lambda expression is either

 (type1 param1, type2 param2, ...) -> expression

or

 (type1 param1, type2 param2, ...) -> { statements; }

The data type for a parameter may be explicitly declared or implicitly inferred by the compiler. The parentheses can be omitted if there is only one parameter without an explicit data type. In the previous example, the lambda expression is as follows

event -> {
    circle.setRadius(circle.getRadius() + 2);
}

The compiler treats a lambda expression as if it is an object created from an anonymous inner class. In this case, the compiler understands that the object must be an instance of EventHandler<ActionEvent>. Since the EventHandler interface defines the handle method with a parameter of the ActionEvent type, the compiler automatically recognizes that event is a parameter of the ActionEvent type, and the statements are for the body of the handle method. The EventHandler interface contains just one method. The statements in the lambda expression are all for that method. If it contains multiple methods, the compiler will not be able to compile the lambda expression. So, for the compiler to understand lambda expressions, the interface must contain exactly one abstract method. Such an interface is known as a functional interface or a Single Abstract Method (SAM) interface.

Session 9
  • Institute of Computer Science
  • Faculty of Science and Technology
  • University of Tartu
In case of technical problems or questions write to:

Contact the course organizers with the organizational and course content questions.
The proprietary copyrights of educational materials belong to the University of Tartu. The use of educational materials is permitted for the purposes and under the conditions provided for in the copyright law for the free use of a work. When using educational materials, the user is obligated to give credit to the author of the educational materials.
The use of educational materials for other purposes is allowed only with the prior written consent of the University of Tartu.
Terms of use for the Courses environment