• Register
0 votes

Problem :

In Java, I want to have something as below :

class MyClazz<T> {
  static void doIt(T object) {
    // More code

But I face below error

“Cannot make a static reference to the non-static type T”

I am unable to understand generics beyond a basic uses and thus unable to make much sense of that. It doesn't help that I wasn't able to find the much info on a internet about a subject.

Could someone clarify if such the use is possible, by the similar manner? Also, why was my original attempt went unsuccessful?

7 5 2
3,870 points

1 Answer

0 votes

Solution :

You should not use the class's generic type parameters in the static methods or static fields. A class's type parameters are only in the scope for instance methods and the instance fields. For a static fields and static methods, they are shared among all of the instances of the class, even instances of different type of parameters, so obviously they cannot depend on the particular type parameter.It does not seem like the problem should require using a class's type parameter.

The better way to handle the things is to put a type parameter in a method itself:

static <U> void doIt(U object)

Hope it fixes your issue.

9 7 4
38,600 points

Related questions

1 vote
1 answer 15 views
Problem: I am very noob in java programming. I was doing my coding practice and wrote this code: public class StaticDemo { int i = 0; public static void main(String[] args) { System.out.println("in main method which is static"); // Trying to access ... -static method instanceMethod() cannot be referenced from a static context instanceMethod(); ^ 3 errors Can anyone help me out to fix this problem?
asked Apr 7 LizzyM 6.1k points
0 votes
1 answer 80 views
Problem : Getting bellow error "non static method cannot be referenced from a static context java"
asked Nov 5, 2019 peterlaw 6.9k points
0 votes
1 answer 15 views
Problem: I have recently joined a new project in WPF C# and at this time I am trying to animate the image to simply move down. I have already found out the "MoveTo" function on an Internet but when I pasted it in my code then the below error occurred: &ldquo; ... button_Click(object sender, RoutedEventArgs e)     {         MoveTo(image, 130);     } } Kindly help me in fixing my above C# code.
asked Jul 28 Raphael Pacheco 4.9k points