I have encountered two ways:
- Where in the code of the Outer class we are creating (by new keyword) the Inner class we can send to the Inner class constructor an instance to his Outer class (using this keywords). This way can be found in ArrayList class implementation of subList method with the code:
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
SubList(AbstractList<E> parent,
int offset, int fromIndex, int toIndex) {
this.parent = parent;
this.parentOffset = fromIndex;
this.offset = offset + fromIndex;
this.size = toIndex - fromIndex;
this.modCount = ArrayList.this.modCount;
}
- Not sending this keyword and then in any place in the Inner class where we want to access ArrayList (outer class) method and properties we can write the following code:
ArrayList.this.arrayListMethod()
instead of writing:
parent.arrayListMethod()
Where parent is the reference to the ArrayList class that was passed by this keyword
My question, will both ways work (if the answer is yes, which one is better)?
I'm apologize the way this question was post, but i have failed in inserting the code under code section. I will be glad if someone can edit it and make it more readable cause i failed in this mission.
Ways to create nested classes in java
here we are talking about class inside class means inner class should not exist if there is no object of outer class example Map contain Entity class without map object there should not be any entity.
Let's come to question, Both the this are doing same work however, using parent is not suitable Because if InnerClass should not contain any reference OuterCall using reference variable.
To understand the need of using className.this as follows