java this(null)

Osm*_*lid 8 java this

我想知道这意味着什么?

public Settings() {
    this(null);
}
Run Code Online (Sandbox Code Playgroud)

上面的代码是"设置"类的构造函数.这(null)在这里意味着什么?

por*_*ida 14

public Settings() {
    this(null); //this is calling the next constructor
}
public Settings(Object o) {
//  this one
}
Run Code Online (Sandbox Code Playgroud)

这通常用于传递默认值,因此您可以决定使用一个或另一个构造函数.

public Person() {
    this("Name"); 
}
public Person(String name) {
    this(name,20)
}
public Person(String name, int age) {
    //...
}
Run Code Online (Sandbox Code Playgroud)


Mec*_*kov 10

这意味着你正在调用一个重载的构造函数,它采用Object某种类型,但你不传递一个对象,而是一个普通的null.

  • 不,它不能@ametren,如果你想这样做,你必须用`super(this)`来做 (2认同)

Kir*_*oll 5

这是一个在同一类中调用另一个构造函数的构造函数。

您大概有以下内容:

public class Settings {
    public Settings() {
        this(null);  // <-- This is calling the constructor below
    }

    public Settings(object someValue) {
    }
}
Run Code Online (Sandbox Code Playgroud)

通常使用此模式,以便您可以为构造函数提供较少的参数(以方便调用者使用),但仍将逻辑包含在一个位置(构造函数被调用)。