电话
400 9058 355
this用于解决成员变量与参数名冲突、调用本类其他构造方法、传递当前对象引用、访问外部类成员;在Lambda中指向外部类,匿名类中指向自身实例。
this
当构造方法或普通方法的参数名和成员变量同名,JVM 无法自动识别你要赋值给谁,必须显式用 this 指向当前对象的成员变量。
this 会导致赋值失败(实际是给参数自己赋值)setter 方法中this. 提示,但
public class Person {
private String name;
public Person(String name) {
this.name = name; // 必须用 this.name,否则 name = name 是参数自赋值
}
}
this(...)
this(...) 必须是构造方法的第一条语句,用于复用初始化逻辑,避免重复代码。不能和 super(...) 同时出现。
public class Point {
private int x, y;
public Point() {
this(0, 0); // 调用下面的构造方法
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
this
当需要把“自己”作为参数传给另一个对象的方法(比如注册监听器、回调、链式调用),就得用 this 显式传递引用。
button.addActionListener(this)(实现 ActionListener 接口时)this 实现 fluent interface,如 builder.setName("a").setAge(18).build()
public class Counter {
private int value = 0;
public Counter increment() {
value++;
return this; // 支持链式调用
}
}
OuterClass.this
非静态内部类(inner class)隐式持有外部类实例引用,但当内部类也有同名成员时,需用 OuterClass.this.field 明确指定访问外部类字段。
static class)不持有外部类引用,不能用 OuterClass.this
public class Outer {
private String data = "outer";
class Inner {
private String data = "inner";
void print() {
System.out.println(Outer.this.data); // 输出 "outer"
System.out.println(this.data); // 输出 "inner"
}
}
}
真正容易出问题的不是 this 的语法,而是它在多层嵌套、匿名内部类、Lambda 表达式中的隐式行为——比如 Lambda 中的 this 指向外部类,而匿名类里的 this 指向自身实例,这种差异在回调场景下极易引发空指针或状态错乱。
邮箱:8955556@qq.com
Q Q:8955556
本文详解如何将Go官方present工具(用于生成HTML5...
PySNMP在不同版本中对SNMP错误状态(errorSta...
time.Sleep仅阻塞当前goroutine,其他gor...
PHPfopen()创建含特殊符号的文件名失败主因是操作系统...
WooCommerce中通过代码为分组产品动态聚合子商品的属...
io.ReadFull返回io.ErrUnexpectedE...
本文详解Yii2中控制器向视图传递ActiveRecord数...
本文详解为何通过wp_set_object_terms()为...
Pytest中使用@mock.patch类装饰器会导致补丁泄...
带缓冲的channel是并发安全的FIFO队列;make(c...