KEMBAR78
Introex 2 | PDF | Anonymous Function | Method (Computer Programming)
0% found this document useful (0 votes)
11 views9 pages

Introex 2

The document explains the concept of functional interfaces in Java, which are interfaces with a single abstract method, and how they can be implemented using anonymous inner classes or lambda expressions. It provides an example with an 'Executable' interface and a 'Runner' class that executes methods, demonstrating both implementation styles. Additionally, it simplifies the concept with a 'Task' interface and a 'Printer' class, highlighting the benefits of using lambda expressions for cleaner and more readable code.

Uploaded by

anup
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)
11 views9 pages

Introex 2

The document explains the concept of functional interfaces in Java, which are interfaces with a single abstract method, and how they can be implemented using anonymous inner classes or lambda expressions. It provides an example with an 'Executable' interface and a 'Runner' class that executes methods, demonstrating both implementation styles. Additionally, it simplifies the concept with a 'Task' interface and a 'Printer' class, highlighting the benefits of using lambda expressions for cleaner and more readable code.

Uploaded by

anup
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/ 9

Functional interface example

explain below example code related to Functional


interface in java, please simplify

Example :-
interface Executable
{ int execute();
}
class Runner
{ public void run(Executable e)
{ System.out.println("run method code....");
int x = e.execute();
System.out.println("return value="+x);
}
};
public class Test
{ public static void main(String[] args)
{ Runner r = new Runner();
//anonymous inner class
r.run(new Executable(){
public int execute()
{ System.out.println("execute method anonymous
block of java code.....");
return 10;
}
});
//lambda expression code
System.out.println("=============");
r.run(() -> {System.out.println("execute method
lambda expression code.....");
return 20;
});
}
}

E:\>java Test
run method code....
execute method anonymous block of java code.....
return value=10
=============
run method code....
execute method lambda expression code.....
return value=20
Observation:-
If you don’t write any code just you want return value
use below code
r.run(() -> 20);
E:\>java Test
run method code....
execute method anonymous block of java code.....

1/9
return value=10
=============
run method code....
return value=20

Sure Anup! Let's simplify and break down the Functional Interface example step by
step.

✅ What is a Functional Interface?


A functional interface is an interface with only one abstract method. It can be
implemented using:

1. Anonymous inner class (old style)

2. Lambda expression (Java 8+)

In your example:

java

interface Executable {
int execute();
}

This is a functional interface because it has only one method: execute() .

✅ Code Overview
Now let’s go line by line.

Interface and Class

java

interface Executable {
int execute(); // abstract method returning an int
}

java

class Runner {
public void run(Executable e) {
System.out.println("run method code....");
int x = e.execute(); // calling execute() on the object
System.out.println("return value=" + x);
}
}

2/9
Runner has a run() method that takes an Executable and runs its execute()

method.

✅ main() method

java

public class Test {


public static void main(String[] args) {
Runner r = new Runner();

🔸 Using Anonymous Inner Class


java

r.run(new Executable() {
public int execute() {
System.out.println("execute method anonymous block of java code.....");
return 10;
}
});

This creates a class without a name (anonymous class) and gives an implementation
of execute() . When you call r.run(...) , the execute() method inside is called.

🔸 Using Lambda Expression


java

System.out.println("=============");

r.run(() -> {
System.out.println("execute method lambda expression code.....");
return 20;
});

This is a lambda expression – it’s a shorter way to implement a functional interface.


It means:

java

Executable e = () -> {
System.out.println("execute method lambda expression code.....");
return 20;
};

✅ Even Shorter: One-liner Lambda

3/9
java

r.run(() -> 20);

If your method only returns a value and no other logic, you can write it like this.

✅ Output Breakdown
java

run method code....


execute method anonymous block of java code.....
return value=10
=============
run method code....
execute method lambda expression code.....
return value=20

And for:

java

r.run(() -> 20);

Output is:

arduino

run method code....


return value=20

Because no System.out.println() is in the execute() block.

✅ Summary
Method Code Style Used in Example

Anonymous class Old Java (pre-8) ✔️ Yes


Lambda expression Java 8 and above ✔️ Yes
One-line lambda Shorter lambda ✔️ Yes
Functional interfaces + Lambda = Clean, modern code ✅
Let me know if you'd like a diagram or simplified analogy.

4/9
Now can you simplify taking better similar code which
is easy to understand and remember

Absolutely, Anup! Let’s create a simpler and easier-to-remember version of the


same concept using a functional interface and lambda expression in a real-world-
like example.

🧠 Think of a real-world task:


Imagine a Printer that prints a message. We'll create a functional interface that
defines what to print, and the Printer will run it.

✅ Simplified Java Example


java

// Step 1: Define a Functional Interface


@FunctionalInterface
interface Task {
void perform(); // only one abstract method
}

// Step 2: Create a Runner class that takes a Task and runs it


class Printer {
public void print(Task task) {
System.out.println("Starting printer...");
task.perform(); // calling perform method
System.out.println("Finished printing.\n");
}
}

// Step 3: Main class


public class Test {
public static void main(String[] args) {
Printer printer = new Printer();

// Way 1: Using Anonymous Inner Class


printer.print(new Task() {
public void perform() {
System.out.println("Printing using anonymous inner class...");
}
});

// Way 2: Using Lambda Expression


printer.print(() -> {
System.out.println("Printing using lambda expression...");

5/9
});

// Way 3: Shortest one-liner if no logic inside


printer.print(() -> System.out.println("One-line lambda printing..."));
}
}

✅ Output:
arduino

Starting printer...
Printing using anonymous inner class...
Finished printing.

Starting printer...
Printing using lambda expression...
Finished printing.

Starting printer...
One-line lambda printing...
Finished printing.

✅ Key Takeaways
Concept Example Code

Functional Interface interface Task {

void perform(); }

Anonymous Class new Task() { public

void perform() {} }

Lambda Expression () -> { /* code */

One-liner Lambda () ->

System.out.println("

Hi")

🧠 Memory Tip
Just remember:

6/9
Functional Interface = 1 Method → Can use Lambda!

You can think of it as:

java

Runner.run(() -> doSomething());

Let me know if you'd like this in diagram or notes form!

sure

Great! Here's a simple visual diagram and quick notes version to help you
remember and understand Functional Interfaces with Lambda Expressions easily.

✅ Functional Interface with Lambda – Visual Diagram


csharp

+---------------------+
| FunctionalInterface|
| Task |
| void perform(); |
+---------+-----------+
|
| (Implemented using...)
v
+-----------------------------+ +-----------------------------+
| Anonymous Inner Class | | Lambda Expression |
| | | |
| printer.print(new Task() { | | printer.print(() -> { |
| public void perform() { | ---> | System.out.println(...); |
| System.out.println(...);| | }); |
| } | +-----------------------------+
| }); |
+-----------------------------+

✅ Key Notes (Easy to Remember)


🟡 What is a Functional Interface?
An interface with only one abstract method

7/9
Example:

java

interface Task {
void perform();
}

🟡 Why Lambda Expressions?


They are a short way to implement a functional interface.

Improves readability and reduces boilerplate.

🟡 Lambda Syntax:
java

() -> {
// method body
}

If method body is one line, you can simplify it:

java

() -> System.out.println("Hello");

🟡 Full Example Recap:


java

interface Task {
void perform();
}

class Printer {
void print(Task task) {
System.out.println("Starting...");
task.perform();
System.out.println("Done.\n");
}
}

public class Test {


public static void main(String[] args) {
Printer printer = new Printer();

// Anonymous class
printer.print(new Task() {
public void perform() {
System.out.println("Old way.");
}
});

8/9
// Lambda
printer.print(() -> {
System.out.println("Lambda way.");
});

// One-liner
printer.print(() -> System.out.println("Shortest way."));
}
}

✅ Practice Tip
💡 Pick any small task like Download , Calculate , or Greet

Write a functional interface for it and implement using lambda!

Would you like a printable PDF-style cheat sheet for this?

9/9

You might also like