public static BTNode<E> treeCopy(BTNode<E> source)
{
if(source == null)
return null;
else
{
BTNode left = BTNode.treeCopy(source.left);
BTNode right = BTNode.treeCopy(source.right);
return new BTNode(source.data, left, right);
}
}
My questions is why can't I use the generic Type E in a static context? I tried search for several answers couldn't find any that make snese.
1 Answer. You can't use a class's generic type parameters in static methods or static fields. The class's type parameters are only in scope for instance methods and instance fields.
A static generic class is exactly as useful as any given static class. The difference is that you don't have to use copy-and-paste to create a version of the static class for each type you want it to work on. You make the class generic, and you can "generate" one version for each set of type parameters.
Generics enable the use of stronger type-checking, the elimination of casts, and the ability to develop generic algorithms. Without generics, many of the features that we use in Java today would not be possible.
The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).
You need to declare the generic type in the method signature. Since this is a static method - it cannot grab generic information from anywhere else. So it needs to be declared right here:
public static <E> BTNode<E> treeCopy(BTNode<E> source)
{
if(source == null)
return null;
else
{
BTNode<E> left = BTNode.treeCopy(source.left);
BTNode<E> right = BTNode.treeCopy(source.right);
return new BTNode(source.data, left, right);
}
}
E
can mean anything. To use E
(as a generic) you need to create an instance of an object. You cannot do this if you have a static method because the generic type-parameters are only in scope for an instance of the class (which includes its instance methods and instance fields).
Static members and fields belong to every instance of the class. So if you had an instance of BTNode<String>
and another instance of BTNode<Integer>
, what exactly should the static treeCopy
be using? String
or Integer
?
There is a workaroud; you have to tell the static method what E
means. So you will have to define it like this:
public static <E> BTNode<E> treeCopy(BTNode<E> source)
It would also help to take a second look at your design and see if this is actually what you want.
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