我在下面的下面的代码:的Java主 - 调用其他方法
public static void main(String args[])
{
start();
}
我得到这个错误:非静态方法start()方法不能从静态上下文引用。
我该如何去做这件事?
我在下面的下面的代码:的Java主 - 调用其他方法
public static void main(String args[])
{
start();
}
我得到这个错误:非静态方法start()方法不能从静态上下文引用。
我该如何去做这件事?
创建您的班级实例并调用该实例的start
方法。 如果你的类名为Foo然后用下面的代码在你main
方法:
Foo f = new Foo();
f.start();
此外,请方法start
静态的,通过它声明为静态的。
希望这可以帮助你..
public class testProgarm {
private static void start() {
System.out.println("Test");
}
public static void main(String[] args) {
start();
}
}
然而,这是不是一个好的做法,使一个方法是静态的。您应该实例化对象并调用对象的方法。如果你的对象没有状态,或者你需要实现一个辅助方法,那么static就是要走的路。
“但是,使方法静态不是一个好习惯。”这真的取决于。如果你没有状态,或者你需要实现一个辅助方法,static就是要走的路。 – helpermethod
@Oliver:谢谢并同意,并在我的回答中提供您的答案 –
一种方法是在主方法内创建另一个类的实例,例如newClass
并在其中调用start()
方法。
newClass class = new newClass();
class.start();
Non static (& instance) methods, so you may need an instance of class to use.
public class TestClass {
public static void main(String[] args) {
start();
TestClass tc = new TestClass();
tc.start1()
}
// Static method
private static void start() {
System.out.println("start");
}
// Non-static method
private void start1() {
System.out.println("start1");
}
}
我建议初学者对Java的书吗?或者至少阅读Oracle提供的教程?你的问题表明你确实没有牢牢掌握最基本的概念,要么真的有帮助。 –
你如何声明你的开始()? –