-2

I created my main use constructor with three parameter passed. the parameter above a default parameter. the goal is to set the first field which is name to be default assume user doesnt input a name. the problem come as for creditLimit and email i get the error below. why is this and what is it i do not understand? and what are the fixes.

- 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;
    }
dave
  • 1
  • 1

3 Answers3

3

The Problem

There seems to be an issue with your first constructor which calls with second constructor with the following parameters at runtime:

this ("Default", 0, null);

This is because the values of creditLimit and email are not set.

  • creditLimit defaults to 0 as that is the default for ints.
  • email defaults to null because it is an empty object reference.

The Solution

To fix this issue, I recommend having some final fields at the top of your class that define default behavior.

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

}

Trade Off

While this may resolve your issue, I would recommend you consider whether or not you want to have defaults for something as specific as a costumer. Depending on your usage, you may want all costumer data to be differentiable, and creating a lot of a default costumers will take that ability away.

Zack R
  • 207
  • 1
  • 11
1

There is a problem with your first constructor, because it will call the second constructor (the one with the parameters), but you just try to set undefined variables to themselves.

Max Vollmer
  • 8,412
  • 9
  • 28
  • 43
GitPhilter
  • 171
  • 9
0

If your goal is to set the first field which is name to be default assume user doesnt input a name, use this constructor

    public VipCustomer() 
    {
       this.name = "Default";
    }

if creditLimit and email is a required value while name is not

    public VipCustomer(int creditLimit, String email) {
        this.name = "Default";
        this.creditLimit = creditLimit;
        this.email = email;
    }
Erwin
  • 460
  • 2
  • 6