

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why can't Java generics be used for static methods?
Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically. By defining a class as generic you are making it type-safe i.e. it can act up on any datatype.
Generics for static methods
We can use generics for static methods
public class GenericMethod { static <T>void sampleMethod(T[] array) { for(int i=0; i<array.length; i++) { System.out.println(array[i]); } } public static void main(String args[]) { GenericMethod obj = new GenericMethod(); Integer intArray[] = {45, 26, 89, 96}; sampleMethod(intArray); String stringArray[] = {"Krishna", "Raju", "Seema", "Geeta"}; sampleMethod(stringArray); Character charArray[] = {'a', 's', 'w', 't'}; sampleMethod(charArray); } }
Output
45 26 89 96 Krishna Raju Seema Geeta a s w t
What we can’t use is static before the type parameters of generic class.
Example
class Student<T>{ static T age; Student(T age){ this.age = age; } public void display() { System.out.println("Value of age: "+this.age); } } public class GenericsExample { public static void main(String args[]) { Student<Float> std1 = new Student<Float>(25.5f); std1.display(); } }
Compile time error
GenericsExample.java:3: error: non-static type variable T cannot be referenced from a static context static T age; ^ 1 error
- Related Questions & Answers
- Why can't static method be abstract in Java?
- Why can't 'kotlin.Result' be used as a return type?
- Why can’t we override static methods in Java?
- Why interfaces don't have static initialization block when it can have static methods alone in java?
- Why can't we define a static method in a Java interface?
- Why can't a Java class be both abstract and final?
- Why we can't initialize static final variable in try/catch block in java?
- Why Java wouldn't allow initialization of static final variable in a constructor?
- Why can't we use the "super" keyword is in a static method in java?
- Is it mandatory to use T for type-parameter, while defining Generics classes/methods in Java?
- Why can't variables be declared in a switch statement in C/C++?
- Why can't girls have all the fun?
- Can I overload static methods in Java?
- Can interfaces have Static methods in Java?
- Why main() method must be static in java?
Advertisements