zoukankan      html  css  js  c++  java
  • 方法引用

    方法引用


    public class Main {
        public static void main(String[] args) {
            //匿名内部类
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello world!");
                }
            };
    
            Thread thread = new Thread(runnable);
            thread.start();
        }
    }
    

    需要使用函数式接口的对象的地方可以使用lambda表达式:

    public static void main(String[] args) {
        //1.
        Runnable runnable = () -> {
            System.out.println("hello world!");
        };
        
        //2.
        Thread thread = new Thread(() -> {
            System.out.println("hello world!");
        });
        thread.start();
    }
    

    有时已经有现成的方法可以完成你想要传递给其他代码的某个动作,此时可以直接将该方法传递:

    public class Main {
        public static void main(String[] args) {
            //1.
            Runnable runnable = Main::myRunnable;
    
            //2.
            Thread thread = new Thread(Main::myRunnable);
            thread.start();
        }
    
        //静态方法
        public static void myRunnable() {
            System.out.println("hello world!");
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            //创建实例
            Main main = new Main();
    
            //1.
            Runnable runnable = main::myRunnable;
    
            //2.
            Thread thread = new Thread(main::myRunnable);
            thread.start();
        }
    
        //非静态方法
        public void myRunnable() {
            System.out.println("hello world!");
        }
    }
    
  • 相关阅读:
    24点游戏算法
    汉诺塔算法
    台阶算法
    质因数分解算法
    全排列递归算法
    DFS 深度优先搜索例题
    容器
    数细胞
    C++栈和队列
    C++STL中vector容器 begin()与end()函数、front()与back()的用法
  • 原文地址:https://www.cnblogs.com/XiaoZhengYu/p/12861484.html
Copyright © 2011-2022 走看看