为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我不能通过引用此关键字来在构造中使用字段变量

为什么我不能通过引用此关键字来在构造中使用字段变量

慕的地10843 2023-08-16 15:57:36
我创建了我的主要用途构造函数并传递了三个参数。默认参数之上的参数。目标是将第一个字段(名称)设置为默认值(假设用户未输入名称)。问题在于信用限额和电子邮件,我收到以下错误。这是为什么?我不明白是什么?以及修复措施是什么。- Cannot refer to an instance field creditLimit while explicitly invoking a  constructor- Cannot refer to an instance field email while explicitly invoking a public class VipCustomer {    private String name;    private int creditLimit;    private String email;    public VipCustomer()     {        this("Default",creditLimit,email);    }    public VipCustomer(String name, int creditLimit, String email) {        // TODO Auto-generated constructor stub        this.name = name;        this.creditLimit = creditLimit;        this.email = email;    }    public String getName()     {        return this.name;    }    public int getCreditLimit()     {        return creditLimit;    }
查看完整描述

3 回答

?
慕村9548890

TA贡献1884条经验 获得超4个赞

问题

您的第一个构造函数似乎存在问题,它在运行时使用以下参数调用第二个构造函数:

this ("Default", 0, null);

这是因为creditLimit 和email 的值没有设置。

  • CreditLimit 默认为 0,因为这是整数的默认值。

  • email 默认为 null,因为它是一个空对象引用。

解决方案

为了解决这个问题,我建议在类的顶部有一些定义默认行为的最终字段。

public class VipCostumer {


    // Change these values to what you would like.

    public static final String DEFAULT_NAME = "Default";

    public static final int DEFAULT_CREDIT = 100;

    public static final String DEFAULT_EMAIL = "example@abc.com";


    public VipCostumer() {

        this(DEFAULT_NAME, DEFAULT_CREDIT, DEFAULT_EMAIL);

    }


    // rest of your code


}

权衡


虽然这可能会解决您的问题,但我建议您考虑是否要为像客户这样具体的东西设置默认值。根据您的使用情况,您可能希望所有客户数据都是可区分的,而创建大量默认客户将剥夺这种能力。


查看完整回答
反对 回复 2023-08-16
?
慕斯王

TA贡献1864条经验 获得超2个赞

您的第一个构造函数有问题,因为它将调用第二个构造函数(带有参数的构造函数),但您只是尝试将未定义的变量设置为自身。



查看完整回答
反对 回复 2023-08-16
?
烙印99

TA贡献1829条经验 获得超13个赞

如果您的目标是将名称的第一个字段设置为默认值假设用户没有输入名称,请使用此构造函数


    public VipCustomer() 

    {

       this.name = "Default";

    }

如果 CreditLimit 和 email 是必填值,而 name 不是必填值


    public VipCustomer(int creditLimit, String email) {

        this.name = "Default";

        this.creditLimit = creditLimit;

        this.email = email;

    }


查看完整回答
反对 回复 2023-08-16
  • 3 回答
  • 0 关注
  • 94 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信