在静态方法JAVA中使用非静态变量 [英] Using a non-static variable in a static method JAVA

查看:157
本文介绍了在静态方法JAVA中使用非静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在编写一个非常大的java代码,在这段代码中我希望它以特定的文件格式输出文件。在这个例子中,它将是一个简单的.txt文件。

So I am writing a very large java code, within this code I want it to output files in a particular file format. In this instance it is going to be a simple .txt file.

我输出的数据是一系列坐标,这些坐标使用在此代码部分之前由用户确定的角度进行旋转。

The data I am outputting is a series of coordinates, these coordinates have undergone rotation using an angle that is determined by the user prior to this code section.

编写文件的代码显然是一个静态方法,但我调用的角度是一个非静态变量...我怎么称呼它并得到它工作?

The code to write the file is obviously in a static method but the angle I am calling is a non-static variable... how do I call this and get it to work?

推荐答案

基本上你必须将包含非静态变量的对象的实例传递给静态函数并访问在那里。

Basically you have to pass an instance of the object containing the non-static variable to the static function and access it there.

这看起来像这样:

public class ObjectToBeWritten {
  private int nonStaticVariable;

  public ObjectToBeWritten() {
      // ...
  }

  public int getNonStaticVariable() {
      return nonStaticVariable;
  }

  public static void outputToTxt(ObjectToBeWritten object) {
      nonStaticVariable = object.getNonStaticVariable();
      // ...
  }
}

然后你只需使用包含非静态变量的对象调用 ObjectToBeWritten.outputToTxt(object)

Then you just call ObjectToBeWritten.outputToTxt(object) with the object that contains the non-static variable.

这篇关于在静态方法JAVA中使用非静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆