区别之一:
匿名内部类使用无限定的this,这个this指的就是该匿名内部类对应的实例。
而lambda表达式使用无限定的this,这个this却是外部类的实例。
有限定的this即指定某个外部类的this,无限定就是没有指定是哪个外部类的this。
不理解?看代码....
匿名内部类的代码
public class Hello {
Hello hello = this;
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println((Object) this == hello);
}
};
public static void main(String... args) {
new Hello().r1.run();
}
}
结果输出为:false
lambda的代码
public class Hello {
Hello hello = this;
Runnable r1 = () -> {
System.out.println((Object)this == hello);
};
public static void main(String... args) {
new Hello().r1.run();
}
}
结果输出为:true
区别之二:
匿名内部类内调用与外部类有相同签名的方法是,实际调用的是该匿名内部类实例的方法。
而lambda调用与外部类有相同签名的方法是,实际调用的是外部类实例的方法。
以toString方法为例,看代码....
匿名内部类代码
public class Hello {
Hello hello = this;
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("匿名内部类调用:" + toString());
}
};
public static void main(String... args) {
Hello hello = new Hello();
hello.r1.run();
System.out.println(hello.toString());
}
}
输出结果为:
匿名内部类调用:c.Hello$1@7852e922
c.Hello@4e25154f
lambda代码:
public class Hello {
Hello hello = this;
Runnable r1 = () -> {
System.out.println("匿名内部类调用:" + toString());
};
public static void main(String... args) {
Hello hello = new Hello();
hello.r1.run();
System.out.println(hello.toString());
}
}
输出结果为:
匿名内部类调用:c.Hello@1218025c
c.Hello@1218025c
总结:lambda表达式与匿名内部类的区别导致lambda表达式与javascript的函数类似了,即在函数内的this关键字指的是调用该函数的对象的引用。。