Spring/JAVA

[Java8 Lambda] this

alsruds 2023. 10. 17. 00:34
🤹‍♂️Java Brains 강의🤹‍♂️

https://www.youtube.com/playlist?list=PLqq-6Pq4lTTa9YGfyhyW2CqdtW9RtY-I3

 

✨ 'This' reference in Lambda

· the instance of a lambda that does not touch 'this' reference → unmodified

· no overriding

 

✨ Lambda vs. Anonymous Inner Class

· Interface

interface Process {
    void process(int i);
}

 

· Lambda : it still refers to the instance that it points to outside of the lambda

public class Main {

    public void doProcess(int i, Process p) {
        p.process(i);
    }

    public void execute() {
        doProcess(10, i -> {
            System.out.println("Value of i is " + i);
            // this : instance off the object on which the execute method is being called
            System.out.println(this);
        });
    }

    public static void main(String[] args) {
        Main thisReference = new Main();
        thisReference.execute();
    }
}

 

· Anonymous Inner Class : inner class instance overrides (value changed)

public class Main {

    public void doProcess(int i, Process p) {
        p.process(i);
    }

    public static void main(String[] args) {
        Main thisReference = new Main();
        thisReference.doProcess(10, new Process() {

            @Override
            public void process(int i) {
                System.out.println("Value of i is " + i);
                // this : new Process() instance that was created in line by using this 'new' keyword
                System.out.println(this);
            }
        });
    }
}

(+) new Process() @override 에 toString 메서드 추가 시 this 출력 안됨