【问题标题】:Why do I need to use class- instead of instancevariable here? [duplicate]为什么我需要在这里使用 class- 而不是 instancevariable? [复制]
【发布时间】:2017-12-31 02:57:18
【问题描述】:

简单的代码,计算给定数组中的数字 n,但我得到一个错误,告诉我将我的实例变量更改为静态。

public class Test{

   int []arr = {4, 21, 4};
   Counter c = new Counter();

   public static void main(String[] args) {
      System.out.println(c.counter(4, arr));
   }
}

public class Counter {

   public int counter(int n, int []ar){  //tried to change method to static - didn't help
       int counter = 0;
       for(int i = 0; i < ar.length; i++){
           if(n == ar[i]){
               counter++;
           }
       }
       return counter;
   }
}

第7行出现错误:将int [] arr和Counter c改为static。

试图使计数器方法静态,但它仍然告诉我将我的数组更改为静态。是什么原因?

【问题讨论】:

  • 第 3 行和第 4 行的变量 arr 和 c 需要分别为 static。方法counter(int, int[])与此无关。
  • 您引用的数组arr 是一个实例变量,但public static void main() 处于静态上下文中(正如static 在签名中已经声明的那样)
  • 否则需要移动到main方法中。
  • 也许可以阅读本指南,了解静态与非静态 beginnersbook.com/2013/05/static-vs-non-static-methods
  • 静态方法只使用类的静态成员。您不能在静态方法中使用类的非静态成员。您必须将它们设为静态或创建 Test 类对象才能使用它们。

标签: java instance-variables class-variables


【解决方案1】:

main 方法是在静态上下文中,不是吗?在Test 中声明的数组和计数器不是静态的。

您永远不能在静态上下文中直接访问非静态成员。

这就是 IDE 建议您将字段设为静态的原因。

将counter 方法更改为静态并不能真正解决问题,因为您仍在尝试在静态上下文中直接访问arr。

解决此问题的另一种方法是同时创建 c 和 arr 局部变量:

public static void main(String[] args) {
    int []arr = {4, 21, 4};
    Counter c = new Counter();
    System.out.println(c.counter(4, arr));
}

【讨论】:

  • 非常清楚,非常感谢先生。
【解决方案2】:

您是从静态函数内部引用两个变量,它们本身需要是静态的以避免错误。

静态方法是可以在没有类对象的情况下调用的方法。这意味着没有this 引用,也没有分配实例变量来访问。相反,静态变量是在加载类时分配的,并且可用于静态和非静态方法。

在您的代码中,问题在于您尝试从 main 方法内部访问变量,该方法始终是静态的。

【讨论】:

    【解决方案3】:

    程序的主方法不能与类的实例绑定,因此它被定义为静态的。

    arr 和c 被声明为Test 的实例变量,因此它们是该类的每个实例的成员。在main 方法的范围内不存在这样的实例。

    静态方法中使用的任何标识符必须是以下之一: a) 同一类的静态成员 b) 局部变量,在方法中声明 c) 在全局命名空间中(例如,另一个类的静态成员,如 Math.pi)

    最简单的解决方案是简单地将arr 和c 的定义移到main 方法中。鉴于您的使用情况,他们没有理由成为该班级的成员。

    public class Test{
    
        public static void main(String[] args) {
            int []arr = {4, 21, 4};
            Counter c = new Counter();
            System.out.println(c.counter(4, arr));
        }
    }
    

    如果您需要它们成为该类的成员,您只需更改原始代码以使其成为静态(即static int []arr = {4, 21, 4};)

    更灵活的解决方案可能涉及使用命令行参数来指定值,或者如果您想使用实例变量,则在 main 方法中实例化类:

    public class Test{
    
        int []arr = {4, 21, 4};
        Counter c = new Counter();
    
        public static void main(String[] args) {
            Test t = new Test();
            System.out.println(t.c.counter(4, t.arr));
        }
    }
    

    但是^这有点恶心。

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 2012-02-26
      • 2010-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多