aspose file tools
The moose likes Beginning Java and the fly likes Non static method cannot be referenced from a static context Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Non static method cannot be referenced from a static context" Watch "Non static method cannot be referenced from a static context" New topic
Author

Non static method cannot be referenced from a static context

Rebecca Witmer
Ranch Hand

Joined: Sep 10, 2004
Posts: 46
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?


SCJP 1.4
Jayesh Lalwani
Ranch Hand

Joined: Nov 05, 2004
Posts: 502
shouldnt that be sortedMap.put ?
Rebecca Witmer
Ranch Hand

Joined: Sep 10, 2004
Posts: 46
Doh!
C. Magmanum
Ranch Hand

Joined: Apr 03, 2004
Posts: 35
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

Joined: Oct 20, 2004
Posts: 280
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 !
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Non static method cannot be referenced from a static context
 
Similar Threads
Is my buffer messed up?
Polymorphic Method Call
Vector usage question
compile time errors
JComboBox (again!!)