首页 > 解决方案 > 为什么我不能通过引用这个关键字在构造中使用字段变量

问题描述

我创建了我的主要使用构造函数,并传递了三个参数。高于默认参数的参数。目标是将第一个名称字段设置为默认值,假设用户没有输入名称。问题来自 creditLimit 和电子邮件,我收到以下错误。这是为什么,我不明白这是什么?什么是修复。

- 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;
    }

标签: java

解决方案


问题

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

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

}

交易

虽然这可能会解决您的问题,但我建议您考虑是否要为特定的客户设置默认值。根据您的使用情况,您可能希望所有客户数据都是可区分的,并且创建大量默认客户将取消该功能。


推荐阅读