Please Explain Java 8 Method Reference to instance Method using class name

后端 未结 4 1985
栀梦
栀梦 2020-12-03 18:04
public interface MyFunc {

    boolean func(T v1, T v2);

}
public class HighTemp {

    private int hTemp;

    HighTemp(){

           


        
4条回答
  •  感动是毒
    2020-12-03 18:56

    Please, correct me if I am wrong, but the way I think about this type of method references (Reference to an Instance Method of an Arbitrary Object of a Particular Type) is that when we pass a method reference, in this case to the counter method, the instance of anonymous class which implements MyFunc interface is created. Then, inside this anonymous class, we override func method which is passed two parameters. And then inside the func method, lessThanTemp method is called like this:

    v1.lessThanTemp(v2); 
    

    So for me this concept looks something like this:

    public class Demo {
        public static void main(String[] args) {
            AnonymousClass an = new AnonymousClass();
            System.out.println(an.apply(new SomeClass(3), 4));
        }
    }
    interface SomeInterface {
        int apply(SomeClass obj, int n);
    }
    
    class SomeClass {
        private int n;
    
        SomeClass(int n) {
            this.n = n;
        }
    
        int add(int n) {
            return this.n + n;
        }
    }
    class AnonymousClass implements SomeInterface {
    
        @Override
        public int apply(SomeClass o, int n) {
            return o.add(n);
        }
    }
    

提交回复
热议问题