• Post Reply Bookmark Topic Watch Topic
  • New Topic

Non static method cannot be referenced from a static context  RSS feed

 
Rebecca Witmer
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have this code in my program:

public Vector sort(Vector averages) {
//put in TreeMap
TreeMap sortedMap = new TreeMap();
for (int l = 0; l < averages.size(); l++) {
Double element = (Double) averages.elementAt(l);
Integer index = new Integer(l);
TreeMap.put(element, index);
}

but JBuilder highlights "put" and says, "Non static method cannot be referenced from a static context". What's it talking about?
 
Jayesh Lalwani
Ranch Hand
Posts: 502
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
shouldnt that be sortedMap.put ?
 
Rebecca Witmer
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Doh!
 
C. Magmanum
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
as u know, most java programs start at main and the syntax for the main method is

it is a static method and it can only make calls to static codes. Make sure the object u want to use is istantiated in your main method and also make sure that u import the java.util.*

I hope it solves your problem, I'm a novice too
 
Amit Saini
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rebecca,
Think of 'static' as 'one per class'.
Static methods and variables are initialized when the class is loaded.
Since static variables and methods dont belong to any object, you cant call them as 'objectName.methodName' or 'objectName.variableName'. You have to prefix the class name like,
className.methodName' or 'className.variableName'

In your case, you're doing TreeMap.put, but does the put() method belong to the TreeMap class or the TreeMap object? If TreeMap was a static class, then your syntax would make sense. However, it is not, so you need to access the put() method with an object of TreeMap.

Hope that helps !
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!