2

I'm messing around with Eclipse(and java in general) for the first time in about a year. among the things I have forgotten is the following:

I have a function (void callvote() that I am hoping will be activated by my main function (that is, automatically, relatively early in the program). I currently have it within the same class (body) as the main function itself.
I try to call it withcallvote(); and get an error, "- Cannot make a static reference to the non-static method callvote() from the type body" my function callvote is, at the moment, in the space below main and simply says

public void callvote() { } am i committing a horrible sin by putting more functions in the same class as main? is this a relatively easy fix that I missed somehow? What does this error mean? Have I woken Azatoth with this code? Thanks in advance, Tormos

tormos
  • 21
  • 1

3 Answers3

1

Without the static modifier callvote is implicitly an instance method - you need an instance of a class to call it.

You could mark it as static also:

public static void callvote() ...

Or create an instance of the declaring class:

MyClass instance = new MyClass();
instance.callvote();
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
1

main() is a static method, meaning you can call it directly from a class whereas non-static members can only be called from an object. In order for you to call the callvote() method you need to first instantiate an object of your class:

public static void main(String [ ] args) {
    MyClass myObject = new MyClass();
    myObject.callvote();
}

Another way to avoid the error is to make you callvote() method static as well, but it's usually not what you want to do (but it depends on the nature of your class and method).

This post describes some of the dangers with the overuse of static methods: Class with single method -- best approach?

Community
  • 1
  • 1
Thorkil Holm-Jacobsen
  • 7,287
  • 5
  • 30
  • 43
0

Try this:

public class Main {
    public static void main(String[] args) {
        new Main().callvote()       
    }   
}

the main() entry point of your java program is static. You cannot call a non static method from a static one.

So you have to instanciate your Class first and call the method after.

juergen d
  • 201,996
  • 37
  • 293
  • 362