Is there a difference between the way Inner class access Outclass methods and properties?

64 views Asked by At

I have encountered two ways:

  1. 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;
}
  1. 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.

1

There are 1 answers

0
Abhishek Bansal On

Ways to create nested classes in java

  1. class inside interface
  2. class inside function
  3. class inside class
  4. static class inside class

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.

class Outer{
 class Inner{
  Outer parent;
 }
}

To understand the need of using className.this as follows


public class A {

    int task(){
        return 0;
    }

    int task3(){
        return 0;
    }

    class Event{

        int task(){
            /// need to use class name because function name are same
            return A.this.task();
        }

        int task2(){
            /// can directly use outer class object
            return task3();
        }
    
    }

}

///     Event obj = new A().new Event();  // to create obj of inner class