Java Method Reference - Double Colon (::) Operator Explained with Examples

Опубликовано: 21 Октябрь 2023
на канале: Anupama
110
7

In this video, I've explained what the double colon operator is in Java and also provided examples to help you understand it better. There are three different types of method references.

1. Reference to a static method.​
2. Reference to an instance method.​
3. Reference to a constructor.​

Example: Reference to a static method.
public class Test {
Test(){
System.out.println("Constructor called");
}
public static void m1(){
System.out.println("Function m1 called");
}
public void m2(){
System.out.println("Function m2 called");
}
}

public class MethodReference {
public static void main(String[] args) {
Runnable r = Test::m1;
Thread thread = new Thread(r);
thread.start();
}
}

Example: Reference to an instance method.​

public class MethodReference {
public static void main(String[] args) {
Test test = new Test();
Runnable r = test::m2;
Thread thread = new Thread(r);
thread.start();
}
}

Example: Reference to a constructor.​
public interface Demo {
Test get();
}
public class MethodReference {
public static void main(String[] args) {
Demo demo= Test::new;
demo.get();
}
}

Thank you,
Anupama


На этой странице сайта вы можете посмотреть видео онлайн Java Method Reference - Double Colon (::) Operator Explained with Examples длительностью часов минут секунд в хорошем качестве, которое загрузил пользователь Anupama 21 Октябрь 2023, поделитесь ссылкой с друзьями и знакомыми, на youtube это видео уже посмотрели 110 раз и оно понравилось 7 зрителям. Приятного просмотра!