Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

Image of how code looks likes

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading