Fix: error: non-static type variable T cannot be referenced from a static context


Sample code:

1. package org.code2care.generics;
2. 
3. public class Sample<T> {
4. 
5.    public static void main(String... args) {
6.        T obj;
7.    }
8. }

Now when you complete this code using javac you get the below compliation error.

% Sample.java:6: error: non-static type variable T cannot be referenced from a static context
	   		T obj;
	   		^
1 error

Why this error?

    The issue occurs at line number 6 because we are trying to declare a generic T type parameter which is of non-static type inside the main method which is of static type.


Fix:

    One of the solutions to this issue can be that you can create a non-static method and then make use of the T type parameter.

    package org.code2care.generics;
    
    public class Sample<T> {
    
        public void nonStaticMethod(T t) {
            System.out.println(t);
        }
    
        public static void main(String[] args) {
            System.out.println(10);
        }
    }
error- non-static type variable T cannot be referenced from a static context

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap