【问题标题】:Why is in Java wrong constructor called? [duplicate]为什么在 Java 中调用了错误的构造函数? [复制]
【发布时间】:2020-12-08 20:14:40
【问题描述】:

这是一个有 2 个构造函数的类:

public class Product {
private String name;
private boolean[] r;
private boolean[] i;

public Product(String name, boolean[] r, boolean[] i) {
    this.name = name;
    this.r = r;
    this.i = i;
}
public Product Product(String name, String r, String i){
    this.name= name;
    this.r= BooleanStringHelper.parse(r,'1');
    this.i= BooleanStringHelper.parse(i, '1');
    return this;
} }

如果我在 main() 中调用以下代码:

Product p = new Product("MyProduct", "000001111100", "111100000011");

然后第一个构造函数被调用,但我想调用第二个构造函数

public Product Product(String name, String r, String i)

为什么调用了错误的构造函数?

【问题讨论】:

  • 你错了。尝试添加打印语句。
  • 因为第二种方法不是构造函数。构造函数没有返回类型
  • 你展示的代码(试图创建一个新的 Product 对象)甚至不应该编译,更不用说运行了。没有可用的构造函数与您的表达式匹配。

标签: java constructor


【解决方案1】:

第二个不是构造函数,而是方法。

【讨论】:

  • 可能会添加“删除返回类型Productreturn this;。”
猜你喜欢
  • 1970-01-01
  • 2021-05-14
  • 1970-01-01
  • 2021-02-18
  • 2014-01-14
  • 1970-01-01
  • 2012-02-28
  • 2015-05-21
相关资源
最近更新 更多