【问题标题】:Keyword 'this' with parenthesis that receive parameters in Java 'this(param1,param2)'. Can it be used in setters?在 Java 'this(param1,param2)' 中接收参数的带括号的关键字'this'。可以在二传手中使用吗?
【发布时间】: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


【解决方案1】:

Java 允许将this.classVar = parameter; this.classVar2 = parameter2; 表达式汇总为this(parameter, parameter2)

不,它没有。您仍然必须在某处编码this.classVar = parameter; this.classVar2 = parameter2;this(parameter, parameter2) 所做的只是调用一个构造函数(如果要将这些参数写入这些字段,则其中必须包含 this.classVar = parameter; this.classVar2 = parameter2; 代码)。

您不能从 setter 调用构造函数。您只能从构造函数中调用构造函数。它用于在单个构造函数中整合逻辑,即使您有多个具有不同参数的构造函数,例如:

public MyContainer(int size) {
    this.size = size;
}
public MyContainer() {
    this(16);
}

在那里,MyContainer 构造函数的零参数版本调用单参数版本,将 16 传递给 size 参数。

【讨论】:

  • 只是补充一点:像this(...) 这样的“显式Cnstructor Invocation”必须是(其他)构造函数的第一条语句
【解决方案2】:

this(nombre, apellidos, residencia, comision) 不会“总结”任何内容。

这只是从构造函数调用类中另一个构造函数的一种方式。

没有办法“总结”任何东西

【讨论】:

    【解决方案3】:
    this(/* zero or more args */);
    

    这是一个构造函数调用。您可以在一个构造函数中使用它来引用另一个构造函数(因为没有更好的名称,'constructor chaining')。

    你不能用普通的方法做同样的事情。如果你想从一个普通的方法中创建一个对象,你可以使用与使用类的外部用户相同的语法:

    new MyClass(/* args */);
    

    从您的代码看来,这不是您想要采用的方法。

    【讨论】:

      猜你喜欢
      • 2013-01-17
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 1970-01-01
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多