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?
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With