Skip to content

Instantly share code, notes, and snippets.

@iamminster
Last active February 8, 2020 00:51
Show Gist options
  • Save iamminster/e51f54e20e196f2137f0ab172d80a04f to your computer and use it in GitHub Desktop.
Save iamminster/e51f54e20e196f2137f0ab172d80a04f to your computer and use it in GitHub Desktop.
How to call method before the constructor (this(...)) . Refer to https://stackoverflow.com/questions/285177/how-do-i-call-one-constructor-from-another-in-java
// Normally in order to call constructor from another constructor, we have to call it from the first line (Java rule)
// Example:
public class MyInteger extends Integer {
private int myIntNumber;
public MyInteger() {
this(0);
}
public MyInteger(int num) {
this(num, 1);
}
public MyInteger(int num, int multiple) {
this.myIntNumber = num * multiple;
}
}
// It is also considered preferrable to call from smallest constructor to the largest
// Also, because of this rule, we can only chain ONE constructor inside another, that means something like below is illegal
public MyInteger() {
this(0);
this(1, 2);
}
// or
public MyInteger() {
super();
this(0);
}
// However, in some rare cases that we truly need to do some stuff before calling another constructor (I could not think of one, though)
// We could do that using static method, like this:
public class MyInteger extends Integer {
private int myIntNumber;
public MyInteger() {
this(0);
}
// Here we can call the absOf() static method to get the absolute value before calling the multiply constructor
public MyInteger(int num) {
this(absOf(num), 1);
}
public MyInteger(int num, int multiple) {
this.myIntNumber = num * multiple;
}
private static int absOf(int num) {
// Note: Math.abs(Integer.MIN_VALUE) will return the most negative number instead of the positive
// because signed integer runs from (-2147483648 ~ 2147483647) so there is no 2147483648
return num >= 0 ? num : (num == Integer.MIN_VALUE ? num : Math.abs(num));
}
}
// Although, it is considered a bad design, and I suggest that the designer should take time and rethink about it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment