【发布时间】:2018-06-11 10:38:18
【问题描述】:
Java 允许将this.classVar = parameter; this.classVar2 = parameter2; 表达式汇总为this(parameter, parameter2)。至少在构造函数中使用。
但是当我在 setter 中从前一种方式(在代码中注释)更改为后一种方式时,此代码不起作用:
class Client {
String nombre, apellidos, residencia;
double comision;
void setClient(String nombre, String apellidos, String residencia, double comision){
this(nombre, apellidos, residencia, comision);
//this.nombre = nombre;
//this.apellidos = apellidos;
//this.residencia = residencia;
//this.comision = comision;
}
}
错误提示:
"call to this must be first statement in the constructor.
Constructor in class Client cannot be applied to given types.
required: no arguments
<p>found: String, String, String, double
<p>reason: actual and formal argument list differ in length" (I haven't created one, just left the default).
那么,这种使用 'this' 的方式是否只对构造函数有效,因此不适合 setter?是否需要显式编码构造函数(如果需要,为什么?)?
【问题讨论】:
-
您正在使用参数列表调用构造函数:
String, String, String, double。没有这样的构造函数。你也不能在方法中调用这样的构造函数。 -
是的。
this仅用于从不同的构造函数调用构造函数。您确实需要对其进行编码,否则您将无法调用它。
标签: java constructor this setter