-
Linking constructors
Another very basic problem i fear but i cannot figure it out
simplified:
what i would like is:
Code:
class constructor {
int value1 = 0;
int value2 = 0;
constructor (int v1, int v2 ) {
// test v1 and v2
this.value1 = v1;
this.value2 = v2;
}
constructor (String string) {
int v1;
int v2;
// convert string to v1, v2
this (v1,v2); // THIS DOESN'T WORK
}
}
This doesn't work because this(v1, v2) must be the first statement of
constructor (String string)
But at that time v1 and v2 are not even initialised. let alone filled.
And I also don't want to duplicate the tests from constructor (int v1, int v2 ) to other constructors
But is there an other solution?
-
solution 1:
Code:
constructor1(int v1, int v2) {
setValues(v1, v2);
}
constructor2(String str) {
v1, v2 = convert();
setValues(v1, v2);
}
private setValues() {... }
solution 2 (and I'd prefer this one):
Code:
class Stuff {
public static Stuff makeFromString(String str) {
v1, v2 = convert();
return new Stuff (v1, v2);
}
public Stuff (int v1, int v2) { ... }
}
-
static conversion methods also work, if you really need it to be a constructor. i.e.
Code:
private static int convertToV1(String conv){...}
private static int convertToV2(String conv){...}
I use this one if I need it as a constructor, but need to call another constructor for whatever reason.
-
Thanks I think i stick to iLuxa's version 1
I prefer that because version 2 is a bit a hidden constructor
and i think at my level clarity is important...
Question how do i make the post [solved]?