-3

Our teacher gave us an exercise the other day and asked to make two constructors, one non parameterized and the other parameterized. Then she asked to initialize an attribute in the parameterized constructor using the initialization from the non-parameterized constructor, basically to initialize it with the same value each time we create a new object.

I've tried making a new object in the same class using the non-parameterized constructor and then taking the initialized value from it but I feel like it is kind of unnecessary.

So is there a method or something to do it more easily?

A sample of the code:

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

0

I think your teacher may refer to something like this:

Compte() {
    code_secret = 1111;
}

Compte(...) {
    this();
    //other initialization goes here
}

In the code above the constructor with parameters calls the unparametrized one using this().
The property code_secret is set to 1111 for any instance of the class.

=======================================

Usually when a constant assignment is involved - and no other initialization code is required - this is more properly achieved declaring the property as final initializing it outside the constructor: ie the constructor doesn't take care of determine a value:

private final int code_secret = 1111;

But for the sake of the exercise the teacher proposed, the first solution applies.

More about final keyword

fantaghirocco
  • 4,761
  • 6
  • 38
  • 48