Here is a problem I face when maintaining and old application, below are the code for demonstration: First, I created a class with field innerComp valued by instance of an anonymous class and a field adjustNum which is used in a method of innerComp:
public class InnerComparator {
private int adjustNum = 0;
public InnerComparator() {
}
public InnerComparator(int adjustNum) {
this.adjustNum = adjustNum;
}
public void setAdjustNum(int adjustNum) {
// adjustNum = adjustNum;
this.adjustNum = adjustNum;
}
private Comparator innerComp = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
System.out.println(adjustNum);
return adjustNum;
}
};
public Comparator getInnerComp() {
return innerComp;
}
public void sort(List list) {
Collections.sort(list, innerComp);
}
}
Here demonstrate how I use it:
public class CheckInnerClassUpdate {
public static void main(String[] args) {
InnerComparator comparator = new InnerComparator();
List<String> list = Arrays.asList(new String[]{"1", "2", "3"});
comparator.sort(list);
comparator.setAdjustNum(1);
comparator.sort(list);
InnerComparator comparator2 = new InnerComparator(1);
// comparator.sort(list);
comparator2.sort(list);
}
}
(Updated) As mentioned answer, typo cause the confusion. I have fix the code and comment out the original code.
I found at least an error in your code:
public void setAdjustNum(int adjustNum) {
adjustNum = adjustNum;
}
This method does nothing because it resets adjustNum passed as parameter to the function. If you need to set the adjustNum field of the class your code must be updated to
public void setAdjustNum(int adjustNum) {
this.adjustNum = adjustNum;
}
So the this.adjustNum
refers to the property of the instance, while adjustNum
(without this) refers to the parameter passed to the function. In this case you really set the adjustNum
calling setAdjustNum
method