Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static/non-static innerclass : The type parameter T is hiding the type T

When I use static nested class, I don't get the warning The type parameter T is hiding the type T. However, when I use the non-static nested class I get the warning.

public class CustomStack<T> {
    private class CustomNode<T>{
        private T data;
        private CustomNode<T> next;

        public CustomNode(T data){
            this.data = data;
        }   

    }
}

I want to know, why don't I get this warning when I use static nested class?

like image 353
John Rambo Avatar asked Jan 21 '26 02:01

John Rambo


1 Answers

Inner classes have a reference to their containing class. Through that reference, the inner class can use the value T defined in the outer class. For example, this compiles:

  public class CustomStack<T> {
    private class CustomNode {
      private T data;
      private CustomNode next;

      public CustomNode(T data) {
        this.data = data;
      }
    }
  }

If you make the inner class static, it can no longer use the T defined in the outer class, it will not compile.

In your posted code, the T parameter of the inner class redefines the T of the outer class. This is confusing, because a reader might think that T means the same thing throughout the file, but it doesn't. When used inside the inner class it will mean something else.

If you want to make the inner class have its own type parameter, then you must call it differently, for example:

public class CustomStack<T> {
    private class CustomNode<U> {
        private U data;
        private CustomNode<U> next;

        public CustomNode(U data) {
            this.data = data;
        }   
    }
}
like image 88
janos Avatar answered Jan 23 '26 19:01

janos