【问题标题】:how to use variable which is declare in another class如何使用在另一个类中声明的变量
【发布时间】:2016-09-27 16:01:54
【问题描述】:

我有一个在一个类中初始化的变量,我想在另一个 java 类中使用它 我想在另一个用于数据库助手类的类中使用collect作为表名我该怎么做.. 提前感谢您抽出时间阅读它:) 我在下面有一个示例代码

public class example()
{
String collect;
//and here i have one spinner 
//and in itemSelected in spinner
//i getting that item like this
String item = getItemslected.toString;
collect=item;
}

【问题讨论】:

  • 您的意思是static 变量吗?

标签: java android


【解决方案1】:

选项:

1.使用静态变量:

声明static String collect; 并从其他类以<YourClassNmae>.collect; 访问它 其中 YourClassName 是您在其中声明静态变量的类

2.使用Application

创建应用程序类扩展Application

public class MyApplication extends Application {

    private String someVariable;

    public String getSomeVariable() {
        return someVariable;
    }

    public void setSomeVariable(String someVariable) {
        this.someVariable = someVariable;
    }
}

在清单中声明应用程序类名,如:

<application 
  android:name=".MyApplication" 
  android:icon="@drawable/icon" 
  android:label="@string/app_name">

然后在您的活动中,您可以像这样获取和设置变量:

// set
((MyApplication) this.getApplication()).setSomeVariable(collect);

// get
String collect = ((MyApplication) this.getApplication()).getSomeVariable();

【讨论】:

  • 只是要知道,如果使用太多扩展应用程序会减慢运行时间,还是与使用静态变量相同?
  • 如果我在主活动中声明一个静态变量并且如果在另一个类中使用它我的数据库类来创建一个类似于 mainactivity.mystatic 变量的表,我正在这个 android 中进行操作:)
【解决方案2】:

您可以将该变量声明为公共静态变量,并且可以在任何其他类中使用它。其他使用方法是使用 set 和 get 方法。

【讨论】:

    【解决方案3】:

    您可以创建一个变量static 并使用Classname.variable 引用它。如果您不想使其成为静态,则需要对该类的实例的引用,然后使用myInstance.variable 引用它。另一种选择是使用方法来返回它(同样,无论是静态的还是非静态的)。

    变量(或方法)也需要适当的访问修饰符: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

    【讨论】:

      【解决方案4】:
      public class Main{
           public static void main(String[] args) {
               System.out.println(Example.test);
               Example.test = "123";
               System.out.println(Example.test);
          }
      }
      
      public class Example{
           public static String test = "This is a Test";
      }
      

      输出:

      This is a test
      123
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-18
        • 1970-01-01
        • 2013-07-02
        • 2023-04-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多