java中this. 和 this::的区别和用法
在Java中,this.
和 this::
是两个不同的概念,有着不同的用法和含义:
1. this.
的用法和含义
含义:this
关键字代表当前对象的引用,this.
用于明确访问当前对象的成员变量或成员方法。在以下几种场景中,经常会用到 this.
:
访问成员变量
当局部变量和成员变量同名时,为了区分二者,需要使用 this.
来访问成员变量。例如:
public class Person {private String name;private int age;public Person(String name, int age) {// 这里的name和age是构造方法的参数,也是局部变量// 通过this.来明确访问成员变量this.name = name; this.age = age;}public void introduce() {System.out.println("My name is " + this.name + ", and I'm " + this.age + " years old.");}
}
在上述代码的构造方法中,使用 this.name
和 this.age
明确表示要操作的是类的成员变量,而不是与成员变量同名的局部变量。
调用成员方法
在一个成员方法中,调用当前对象的其他成员方法时,this.
通常可以省略,但在某些情况下,比如需要明确强调是当前对象的方法,或者在匿名内部类中访问外部类的成员方法时,会使用 this.
。例如:
public class Animal {public void eat() {System.out.println("Animal is eating.");}public void drink() {// 这里可以省略this.,但加上也能明确表示是当前对象的eat方法this.eat(); System.out.println("Animal is drinking.");}
}
作为方法参数传递
可以将 this
作为参数传递给其他方法,以便在其他方法中操作当前对象。例如:
public class Car {private String brand;public Car(String brand) {this.brand = brand;}public void showBrand(Car car) {System.out.println("The brand of the car is " + car.brand);}public void introduce() {// 将当前对象this作为参数传递给showBrand方法showBrand(this); }
}
2. this::
的用法和含义
含义:this::
是Java 8中引入的方法引用语法的一种形式,它表示对当前对象实例方法的引用, 用于将方法作为参数传递给其他方法,通常结合函数式接口一起使用。
使用场景
在使用函数式接口的地方,当你想传递一个方法而不是一个Lambda表达式时,可以使用方法引用。例如,在 java.util.stream.Stream
的操作中:
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;class Product {private String name;private double price;public Product(String name, double price) {this.name = name;this.price = price;}public void printDetails() {System.out.println("Product: " + name + ", Price: " + price);}
}public class MethodReferenceExample {public static void main(String[] args) {List<Product> productList = new ArrayList<>();productList.add(new Product("Book", 19.99));productList.add(new Product("Pen", 2.99));// 使用this::printDetails方法引用productList.forEach(this::printDetails); }
}
在上述代码中,productList.forEach(this::printDetails);
表示对 this
(当前对象,这里是 MethodReferenceExample
的实例 ,虽然在 main
方法中,this
指向的是 MethodReferenceExample
的实例)的 printDetails
方法的引用,它等价于 productList.forEach(product -> product.printDetails());
这样的Lambda表达式。
3. 两者的区别
- 本质不同:
this.
主要用于访问当前对象的成员变量和成员方法,是对对象成员的直接访问操作;而this::
是一种方法引用语法,用于将当前对象的实例方法作为一个可传递的对象(类似函数式编程中的函数传递),传递给其他需要函数式接口作为参数的方法。 - 语法和使用场景不同:
this.
广泛应用于类的各种成员方法中,用于明确访问对象成员;this::
则主要出现在需要使用函数式接口的地方,比如在流操作、线程构造等场景中传递方法。