'How to set a default value in class when an object is created
I want to make card number of the customer is always set to -1 when a new customer is created.
public Customer(int cardNumber, int yearOfBirth) {
this.cardNumber = cardNumber;
this.yearOfBirth = yearOfBirth;
}
public int getCardNumber() {
return cardNumber;
}
public void setCardNumber(int cardNumber) {
this.cardNumber = cardNumber;
}
Solution 1:[1]
This is one way to do it. Add an initializer to the field declaration.
public class Customer {
private int cardNumber = -1;
private int yearOfBirth;
public Customer(int yearOfBirth) {
this.yearOfBirth = yearOfBirth;
}
public int getCardNumber() {
return cardNumber;
}
public void setCardNumber(int cardNumber) {
this.cardNumber = cardNumber;
}
}
Another alternative would be to explicitly initialize the field to its default value in the constructor; e.g.
public Customer(int yearOfBirth) {
this.yearOfBirth = yearOfBirth;
this.cardNumber = -1;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |