让构造函数访问静态变量

时间:2011-12-14 20:54:39

标签: java constructor static-variables

现在我有两个.java文件 Main.java:

public class Main {
    static int integer = 15;
    NeedInteger need = new NeedInteger();
}

和NeedInteger.java

public class NeedInteger {
    System.out.println(integer);
}

这当然非常简化,但有什么方法可以实现这个目标吗?

6 个答案:

答案 0 :(得分:2)

正如许多人所回答的那样,正确的方法是将值传递给新类的构造函数。

如果由于某种原因你不能这样做,那么你可以在Main中使用一个公共静态访问器方法来访问该值(这比仅将该字段公开更好一点。)

E.g。

public class Main
{
  private static int integer = 15;

  public static int getInteger()
  {
    return integer;
  }
}

public class NeedInteger
{
  public NeedInteger()
  {
    int integer = Main.getInteger();
  }
}

答案 1 :(得分:1)

将变量传递给类构造函数。

数组引用就是 - 引用。

或者你可以传入类本身,或使用静态(meh)。

答案 2 :(得分:1)

将构造函数添加到NeedInteger(如果您还需要存储,还可以选择成员):

public class NeedInteger {

    private int integer;

    public NeedInteger(int integer) {
        this.integer = integer;
        System.out.println(integer);
    }
}

然后在创建实例时传递您的值:

public class Main {
    static int integer = 15;
    NeedInteger need = new NeedInteger(integer);
}

答案 3 :(得分:1)

你必须做一些糟糕的juju移动(比如使用全局变量)或将它传递给构造函数。

注意:你的

public class NeedInteger {
    System.out.println(integer);
}

没有方法。我建议将所有这些改写为:

public Class NeedInteger {
    NeedInteger(int integer) {
    System.out.println(integer);
    }
}

如果你真的希望在施工时完成工作。

编辑:从上面的评论开始。

相反,让课程结构如下:

public Class NeedStringArray {
       NeedStringArray(String[][][] stringArr) {
           //work with String array here
       }
}

这没有真正的额外开销,因为实际的数组不会被传递,而只是对它的引用。您可能希望将数组设置为final或其他内容,以避免在NeedStringArray构造函数中对其进行编辑。

答案 4 :(得分:1)

整数是私有的,因此NeedInteger无法访问它。你必须公开或使用setter或getter,你需要使用Main.integer,因为它是静态的。

通常,您在构造函数中进行设置。

答案 5 :(得分:1)

根据您的评论我会说您可以在singleton中托管您的数组 或者像其他人建议的那样,第二个类接受构造函数中对数组的引用。然后,您可以使用依赖注入框架(例如Guice)来连接它们

相关问题