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);
}
}
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Java,
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
More Posts:
- Cmd command get current directory location - Windows
- SharePoint List redirect user after submitting form NewForm.aspx - SharePoint
- List of Java JDBC Database Driver Jars, Classes and URLs Details - Java
- Bootstrap Nav Menu Dropdown on hover - Bootstrap
- Implementing Merge Sort Algorithm in Java Program - Java
- Fix [oh-my-zsh] Cant update: not a git repository - Git
- Make div element draggable using jQuery - jQuery
- Terminal display next month Calendar - Linux