【问题标题】:Should the main method not be declared static or should the other method be declared static? Java [duplicate]主要方法不应该声明为静态的还是应该将其他方法声明为静态的? Java [重复]
【发布时间】:2019-08-07 15:37:37
【问题描述】:
public class Question {  
    public void doThing() {}  
    public static void main(String[] args) {      
        doThing();  
    } }

是否应该将 doThing() 方法声明为静态以在 main() 中使用?

main() 方法不应该声明为静态的吗?

他们都没有给我一个错误,但你会说哪个是对的或错的,为什么?

【问题讨论】:

    标签: java methods static-methods


    【解决方案1】:

    由于你已经写了代码,main()方法将无法调用doThing():main是静态的; doThing 不是。

    你可以解决这个问题:

    1. 将 doThing 设为静态,或

    2. 实例化 Question 并调用 doThing:

      类问题{ 公共无效doThing(){ }

      public static void main(String[] args) {
          Question q = new Question();
          q.doThing();
      }
      

    【讨论】:

      猜你喜欢
      • 2014-11-02
      • 2014-05-12
      • 1970-01-01
      • 2014-11-09
      • 1970-01-01
      • 1970-01-01
      • 2014-02-04
      • 2018-07-10
      • 2014-05-06
      相关资源
      最近更新 更多