• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic error

 
meeta gaur
Ranch Hand
Posts: 305
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Box.java:13: error: non-static type variable String cannot be referenced from a static context
public static void main(String[] args)
^
1 error

 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
meeta gaur
Ranch Hand
Posts: 305
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, why that compile error occurred ?
 
Matthew Brown
Bartender
Posts: 4565
8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic