| Author |
Generic error
|
meeta gaur
Ranch Hand
Joined: Dec 05, 2012
Posts: 225
|
|
Box.java:13: error: non-static type variable String cannot be referenced from a static context
public static void main(String[] args)
^
1 error
|
OCAJP
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12911
|
|
In this example "String" does not mean what you think it does.
It is not the name of the class java.lang.String. Instead, you've declared a type parameter in line 1, which is confusingly named "String".
Normally people use single upper case letters for type variables, for example "T", so you'd write "class Box<T>" in line 1. But you can name a type parameter anything you like, including the name of an existing class such as "String".
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
meeta gaur
Ranch Hand
Joined: Dec 05, 2012
Posts: 225
|
|
|
Thank you, why that compile error occurred ?
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3791
|
|
|
As Jesper said, you've used String as a generic type variable, and it's clashing with the class String. The generic type takes precedence, so on line 10 that's what the compiler things you're referring to. And because the type variable applies to specific instances of Box, it can't be used in a static context.
|
 |
 |
|
|
subject: Generic error
|
|
|