Home > other >  Declaring a class inside vs outside on outer class
Declaring a class inside vs outside on outer class

Time:12-20

Might having an inner class with a generic type name that holds the same name of the generic type of the outer class lead to errors with the code later on? Do we have to have different generic names for the nested classes? The following is an example:

public class LinkedList<E> {
   // add state and methods
    private class Node<E> {
        //add state and methods
    }
}

Compared to

private class Node<E> {
    //add state and methods
}
public class LinkedList<E> {
    // add state and methods
}

CodePudding user response:

When we use inner classes, an instance of an inner class is always bound to a concrete instance of the outer class. Hence, in the first example, we can drop the generic type on the inner class:

class LinkedList<E> {
  class Node {
    private final E data;

    public Node(E data) {
      this.data = data;
    }

    public E getData() {
      return data;
    }
  }
}

Ideone demo

CodePudding user response:

You asked whether it causes errors later on and that really depends on what you're trying to accomplish. Based on your example, I assume that you want both classes to use the same generic type. In that case you should have a look at @Turing85's answer.

The nested class example from your post will compile without errors, though some code inspection tools might give you warnings for the shadowed generic type E. For this reason, but most importantly for the sake of maintainability code, you should probably use different names for the generic types. Both classes have their own declaration of E and these are not related to each other in any way. Reusing the same name for different generic types will confuse you and other developers down the road.

Have a look at this question that describes various solutions for the same problem.

  •  Tags:  
  • java
  • Related