0% found this document useful (0 votes)
23 views28 pages

Interfaces and Lambda Expressions

Uploaded by

gyangmargitar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views28 pages

Interfaces and Lambda Expressions

Uploaded by

gyangmargitar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

INTERFACES AND LAMBDA

EXPRESSIONS
INTERFACES AND LAMBDA
EXPRESSIONS
OBJECTIVES:
 KNOW WHAT AN INTERFACES IS
 UNDERSTAND THE VARIOUS TYPES OF
INTERFACES
 KNOW WHAT A LAMBDA
EXPRESSION IS
 UNDERSTAND THE VARIOUS TYPES OF
LAMBDA EXPRESSIONS
INTERFACES
 An interface describes a set of methods that can
be called on an object, but does not provide
concrete implementations for all the methods.
You can declare classes that implement (i.e.,
provide concrete implementations for the
methods of) one or more interfaces.
 Each interface method must be declared in all the
classes that explicitly implement the interface.
Once a class implements an interface, all objects
of that class have an is-a relationship with the
interface type, and all objects of the class are
guaranteed to provide the functionality described
by the interface. This is true of all subclasses of
that class as well.
INTERFACES
Usefulness of Interfaces:
 Interfaces are particularly useful for
assigning common functionality to
possibly unrelated classes. This allows
objects of unrelated classes to be
processed polymorphically— objects of
classes that implement the same interface
can respond to all of the interface
method calls.
INTERFACES
Standardizing Interactions
 Interfaces define and standardize the ways in
which things such as people and systems can
interact with one another.
Using an Interface
 To use an interface, a concrete class must specify
that it implements the interface and must
declare each method in the interface with the
signature specified in the interface declaration.
USING INTERFACES CONT’D
 To specify that a class implements an
interface add the implements keyword and
the name of the interface to the end of your
class declaration’s first line. A class that does
not implement all the methods of the
interface is an abstract class and must be
declared abstract.

 Implementing an interface is like signing a


contract with the compiler that states, ―I will
declare all the methods specified by the
interface or I will declare my class abstract.‖
INTERFACES
Declaring Interfaces:
 Use the keyword: interface. E.g. to
declare an interface called Payable having
an abstract method: pay and a constant:
MAX_DISCOUNT_RATE set at 5%.
public interface Payable {
public abstract double pay();
public static final double MAX_DISCOUNT_RATE
= 0.05;
} // end interface Payable
INTERFACES
The interface may also be declared thus:
public interface Payable {
double pay();
double MAX_DISCOUNT_RATE = 0.05;
} // end interface Payable

NOTE:
 Methods defined interfaces are implicitly
public and abstract.
 Values are implicitly public, static, and final.
INTERFACES
 Interfaces are implemented and not
extended. The code below shows how the
Payable interface is implemented by two
disparate classes: Employee and Invoice.
 This implies that objects of both classes
are also indirect classes of Payable.
 Note that any class that implements an
interface must declare the methods of the
interface else it must be declared as
abstract.
IMPLEMENTING INTERFACES
public class Employee implements Payable {
private double basicPay = 20500.25;
private int hrsWorked = 20;

public double payment() {


double basicPay * hrsWorked;
} // end method payment

public static void main( String[ ] args ) {


Employee employee = new Employee();
System.out.printf( ―Gross pay: %,.2f\n‖, employee,payment());
} // end method payment

} // end class Employee


IMPLEMENTING INTERFACES
public class Invoice implements Payable {
private double costPrice = 9500.50;
private int qty = 5;

public double payment() {


double costPrice * qty;
} // end method payment

public static void main( String[ ] args ) {


Invoice invoiceObj = new Invoice();
System.out.printf( ―Total Cost : %,.2f\n‖, invoiceObj,payment());
} // end method payment

} // end class Invoice


LAMBDA EXPRESSIONS
LAMBDA EXPRESSIONS. What are they?
 A lambda expression is, essentially, an
anonymous (that is, unnamed) method.
However, this method is not executed on its
own. Instead, it is used to implement a method
defined by a functional interface aka
Single Abstract Method (SAM).
 Thus, a lambda expression results in a form
of anonymous class. Lambda expressions are
also commonly referred to as closures.
LAMDA EXPRESSIONS
 A functional interface (aka Single
Abstract Method) is an interface that
contains one and only one abstract method.
Normally, this method specifies the intended
purpose of the interface. Thus, a functional
interface typically represents a single action.

 A functional interface defines the target


type of a lambda expression. Here is a key
point: a lambda expression can be used only
in a context in which a target type is
specified.
LAMDA EXPRESSIONS
Lambda Expression Fundamentals
 The lambda expression introduces a new
syntax element and operator into the Java
language. The new operator, sometimes
referred to as the lambda operator or the
arrow operator, is –>.
 It divides a lambda expression into two
parts. The left side specifies any parameters
required by the lambda expression. On the
right side is the lambda body, which specifies
the actions of the lambda expression.
LAMBDA EXPRESSIONS
Java defines two types of lambda bodies:
 Single Expression, and
 Block of code (Block Lambda).

We will begin with lambdas that defines a


single expression.
Lambda Expression: Single
Expression.
Syntax/General Form:
 () -> expression;
 ( identifier ) -> expression;
 ( dataType identifier ) -> expression

*NOTE: dataType is optional as Java can


infer the appropriate type based on the
usage (expression) of the identifier or
target type.
Single Expression Lambdas
 () -> 9.8; // Evaluates to a constant
 (n) -> n / 2;
 n -> n / 2;
 (x) -> (x % 2) == 0;
 ( int x) -> 1.0/x;
 (x) -> 1.0/x;
 ( n, m ) -> n > m;
 ( bPay, hrs ) -> bPay * hrs;
Implementing Lambda Expressions
 Lambda expressions on there own are
not useful, they require an Interface.
 Consider the interface: Payable presented
earlier:
public interface Payable {
public abstract double pay();
public static final double MAX_DISCOUNT_RATE = 0.05
} // end interface Payable
Implementing Lambda Expressions
 Next, create a variable of the Interface:
Payable grossPay;
 Assign the Lambda expression to the variable.
(Ensure that all required data have been declared)
int hoursWorked;
double payPerHr = 25300.25;
grossPay = () -> hoursWorked * payPerHr;
 Invoke the method defined in the Interface via a
variable of the Interface:
 System.out.printf( ―Gross Pay: %,.2f\n‖,
grossPay.payment() );
Block Lambda Expressions
Format/General Form:
( parameterList ) -> {
statements;
[return;]
};
where:
 parameterList: may be empty and may be one or
more parameters.
 statement: one or more instructions to be
executed.
 The return statement is required if a value is to
be returned.
Block Lambda Expressions
Let’s see a Block Lambda in action. First we
need an Interface:
public interface Sequenceable {
// a: starting value, d: step value, n:
number of terms
void generateSeries( int a, int d, int n );
} // end interface Sequenceable
Block Lambda Expressions
 Write a Lambda expression that generates a
series of integer numbers given the starting
number, common difference and the number
of terms to generate:
 Sequenceable oddNos = (a, d, n) - > {
for( int c = a; c <= n; c += d )
System.out.printf( ―%d ―, c );
System.out.println();
};
Block Lambda Expressions
Implementing the Lambda:
int start = 1, diff = 2, nTerm = 10;
oddNos.generateSeries( start, diff, nTerm );

Sequenceable e_toomuch;
start = 2;
e_toomuch = ( a, d, n ) -> {
int counter = a;
while( counter <= n ) {
System.out.printf( ―%d\n‖, counter );
counter += d;
} // end while
}; // end block lambda
More Examples – Block Lambda
public interface Accumulateable {
double akowonJo(double x[ ] );
} // end interface Accumulateable
---------------------------------------------------
double kudi[ ] = { 10.15, 5.25, 12.75, 7.15 };
Accumulateable addache;
addache = ( owo ) -> {
double s = 0;
for(double naira : owo )
s += naira;
return s;
};
More example continued
double totalKudi = addache.akowonjo( kudi );
JOptionPane.showMessageDialog( null,
String.format(―Total amount in naira: ―
+ ―%,.2f‖, totalKudi );
 Lets consider yet another example:
// A functional interface that takes two int parameters
// and returns a boolean result.
interface NumericTest {
boolean test( int n, int m );
} // end functional interface
More example continued
 NumericTest isFactor = (n, d) -> (n % d) == 0;
 if(isFactor.test(10, 2))
 System.out.println("2 is a factor of 10");
 if(!isFactor.test(10, 3))
System.out.println("3 is not a factor of 10");
System.out.println();

 NumericTest lessThan = (n, m) -> (n < m);


 if( lessThan.test( 2, 10 ) )
System.out.println( ―2 is less than 10― );
 if( !lessThan.test(10, 2 ) )
System.out.println( "10 is not less than 2― );
System.out.println();
Generic Functional Interfaces
 A lambda expression, itself, cannot specify
type parameters. Thus, a lambda expression
cannot be generic. (Of course, because of
type inference, all lambda expressions
exhibit some ―generic-like‖ qualities.)
 However, the functional interface associated
with a lambda expression can be generic.
 In this case, the target type of the lambda
expression is determined, in part, by the type
argument or arguments specified when a
functional interface reference is declared.
Generic Functional Interfaces
// A generic functional interface with two parameters that returns a
boolean result.
 interface SomeTest< T > {
 boolean test(T n, T m);
 }

 SomeTest< Integer > isFactor = (n, d) -> (n % d) == 0;


 if( isFactor.test( 10, 2 ) )
 System.out.println("2 is a factor of 10");
 System.out.println();

 SomeTest< Double > isFactorD = (n, d) -> (n % d) == 0;


 if( isFactorD.test( 212.0, 4.0 ) )
 System.out.println( "4.0 is a factor of 212.0― );
 System.out.println();

You might also like