java 中 this 和 this() 有什么区别
What are the differences between this and this() in java
请确认我是 this
关键字引用它拥有的 class 和 this()
方法引用它拥有的 class 构造函数。
class Tester {
private String blogName;
public Tester() {
this("Whosebug");
}
public Tester(String str) {
this.blogName = str;
}
public String getBlogName() {
return blogName;
}
}
如果它们之间还有其他差异,这对我有帮助。
第一个例子在默认构造函数中调用了重载的构造函数。您可以通过这种方式调用所有重载的构造函数。它必须是构造函数中的第一行,就像调用 super() 一样。
第二个显示特殊名称 this
如何引用 class 中的当前实例。只需要解决名称重复问题:
public class ThisDemo {
private static final String DEFAULT_VALUE = "REQUIRED";
private String value;
public ThisDemo() {
this(DEFAULT_VALUE);
}
publi ThisDemo(String value) {
// Required here because the private member and parameter have same name
this.value = value;
}
public String getValue() {
// Not required here, but I prefer to add it.
return value;
}
}
this
是对代表当前方法被调用的对象的引用。 this(anything)
是对构造函数的调用。
this("Whosebug");
正在调用 class 中的另一个构造函数(这称为委托构造函数)。
this.blogName= str1;
正在分配对 str1
所引用的 字段 blogName
的引用。本例中的 this
是多余的,但用于消除字段名称与同名函数参数的歧义。
this
是Java中的关键字,表示class的当前实例。
this("Whosebug")
正在调用 class 中的构造函数,这将是一个重载调用。您可以通过这种方式调用相同 class 的任何其他构造函数。
请确认我是 this
关键字引用它拥有的 class 和 this()
方法引用它拥有的 class 构造函数。
class Tester {
private String blogName;
public Tester() {
this("Whosebug");
}
public Tester(String str) {
this.blogName = str;
}
public String getBlogName() {
return blogName;
}
}
如果它们之间还有其他差异,这对我有帮助。
第一个例子在默认构造函数中调用了重载的构造函数。您可以通过这种方式调用所有重载的构造函数。它必须是构造函数中的第一行,就像调用 super() 一样。
第二个显示特殊名称 this
如何引用 class 中的当前实例。只需要解决名称重复问题:
public class ThisDemo {
private static final String DEFAULT_VALUE = "REQUIRED";
private String value;
public ThisDemo() {
this(DEFAULT_VALUE);
}
publi ThisDemo(String value) {
// Required here because the private member and parameter have same name
this.value = value;
}
public String getValue() {
// Not required here, but I prefer to add it.
return value;
}
}
this
是对代表当前方法被调用的对象的引用。 this(anything)
是对构造函数的调用。
this("Whosebug");
正在调用 class 中的另一个构造函数(这称为委托构造函数)。
this.blogName= str1;
正在分配对 str1
所引用的 字段 blogName
的引用。本例中的 this
是多余的,但用于消除字段名称与同名函数参数的歧义。
this
是Java中的关键字,表示class的当前实例。
this("Whosebug")
正在调用 class 中的构造函数,这将是一个重载调用。您可以通过这种方式调用相同 class 的任何其他构造函数。