Java 和 main()
大约一年来我第一次摆弄 Eclipse(以及一般的 java)。我忘记的事情如下:
我有一个函数(void callvote()),我希望它能被我的主函数激活(也就是说,在程序中相对较早的时候自动激活)。我目前在同一个函数中拥有它类(主体)作为主函数本身。
我尝试使用 callvote();
调用它并收到错误,“- 无法从类型主体对非静态方法 callvote() 进行静态引用” 我的函数 callvote 目前位于 main 下面的空间中,只是简单地说
public void callvote() { }
通过将更多函数放在与 main 相同的类中,我是否犯了可怕的罪过? 这是一个相对简单的修复,但我不知何故错过了? 这个错误是什么意思? 我用这段代码唤醒了阿扎托斯吗? 提前致谢, 托莫斯
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果没有
static
修饰符,callvote
隐式地是一个实例方法 - 您需要一个类的实例来调用它。您也可以将其标记为静态:
或者创建声明类的实例:
Without the
static
modifiercallvote
is implicitly an instance method - you need an instance of a class to call it.You could mark it as static also:
Or create an instance of the declaring class:
main() 是一个静态方法,这意味着您可以直接从类中调用它,而非静态成员只能从对象中调用。为了让您调用 callvote() 方法,您需要首先实例化类的对象:
避免错误的另一种方法是使您的 callvote() 方法也成为静态,但这通常不是您想要做的(但这取决于您的类和方法的性质)。
这篇文章描述了过度使用静态方法的一些危险:具有单一方法的类-- 最好的方法?
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:
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?
试试这个:
java 程序的
main()
入口点是静态的。您不能从静态方法调用非静态方法。因此,您必须先实例化您的类,然后再调用该方法。
Try this:
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.