::
(double colon operator).
object::instanceMethodName
@FunctionalInterface
interface MyInterface
{
void greet();
}
class Greeting
{
void sayHello()
{
System.out.println("Hello from instance method!");
}
}
public class MainApp
{
public static void main(String[] args)
{
Greeting g = new Greeting();
// Way 1 : Using Lambda
MyInterface obj1 = () -> g.sayHello();
obj1.greet();
// Way 2 : Using Method Reference
MyInterface obj2 = g::sayHello;
obj2.greet();
}
}
Hello from instance method! Hello from instance method!
ClassName::instanceMethodName
@FunctionalInterface
interface MyInterface
{
void displayMsg(String msg);
}
public class MainApp
{
public static void main(String[] args)
{
// Way 1 : Using Lambda
MyInterface obj1 = (msg) -> System.out.println(msg);
obj1.displayMsg("Hello World!");
// Way 2 : Using Method Reference
MyInterface obj2 = System.out::println;
obj2.displayMsg("Hello World!");
}
}
Hello World! Hello World!
ClassName::staticMethodName
@FunctionalInterface
interface MyInterface
{
void display();
}
class Demo
{
static void showMessage()
{
System.out.println("Hello from static method!");
}
}
public class MainApp
{
public static void main(String[] args)
{
// Way 1 : Using Lambda
MyInterface obj1 = () -> Demo.showMessage();
obj1.display();
// Way 2 : Using Method Reference
MyInterface obj2 = Demo::showMessage;
obj2.display();
}
}
Hello from static method! Hello from static method!
ClassName::new
@FunctionalInterface
interface MyInterface
{
Greeting getGreeting();
}
class Greeting
{
Greeting()
{
System.out.println("Greeting object created!");
}
}
public class MainApp
{
public static void main(String[] args)
{
// Way 1 : Using Lambda
MyInterface obj1 = () -> new Greeting();
obj1.getGreeting();
// Way 2 : Using Constructor Reference
MyInterface obj2 = Greeting::new;
obj2.getGreeting();
}
}
Greeting object created! Greeting object created!
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.