[英]How can I reference a variable within a method in another method in the same class (Java)?
[英]How to reference a variable in another class in java?
我個人現在不在我的電腦上,所以我不能分享我的代碼,但我可以嘗試重寫它的一個簡單部分。
public class whatever()
{
public int test;
public String one = "placeholder" //to be filled later
public static void main(String[] args)
{
}
}
在另一個班級,
public class test1()
{
public static void main(String[] args)
{
test = 1;
}
}
在類test1
,我收到一條錯誤消息,說 test 未定義。
您不能像這樣共享變量 - 一個班級不會以您呈現的方式了解變量。
移動變量的一種方法,您可以先在主類中聲明它。
public static void main(String[] args) {
String s = "test";
}
然后編寫一個具有方法的類,該方法接受一個參數來匹配您的變量。
public class OtherClass {
public void methodTest(String s) {
//code goes here
}
}
在原來的類上,需要實例化新的類
OtherClass oc = new OtherClass();
然后可以調用該方法並傳入所需的參數
oc.methodTest(s);
主類現在看起來像:
public static void main(String[] args) {
String s = "test";
otherClass oc = new OtherClass();
oc.methodTest(s);
}
其他類看起來像(帶有簡單的打印語句):
public class OtherClass {
public void methodTest(String s) {
System.out.println(s);
}
}
這將打印s
的值
我能夠通過導入另一個類來做到這一點。 這是我的第一堂課:
import package1.SecondClass;
public class FirstClass {
public static void main(String[] args) {
int i = SecondClass.varToRef;
System.out.println(i);
}
}
打印出 8. 我的第二堂課:
package package1;
public class SecondClass {
public static int varToRef = 8;
public static void main(String[] args) {
}
}
我只能在主方法之外引用該變量,創建和引用基本上就像 SecondClass 的公共靜態字段一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.