[英]Accessing the int value outside of the method
我在Test
類中有一個方法A
,它生成一個數字a
和b
,這是它的代碼:
public class Test
{
int a,b;
public void A()
{
a = currentMenu.getCurrentFocusedItem().getItemID();
b = currentMenu.getMenuID();
System.out.println("Inside A ()" + a + " &&" + b);
}
public void B()
{
System.out.println("Inside B ()" + a + " &&" + b);
}
}
現在,我想在同一方法中將a
和b
int
值添加到另一個方法B()
中
類文件。 需要一些指針
您可以在instance
初始化block
獲得a和b值
public class TestClass {
int a,b;
{
a= 10;
b =45;
}
public void A() {
System.out.println("Inside A ()" + a + " &&" + b);
}
public void B() {
System.out.println("Inside B ()" + a + " &&" + b);
}
}
使用此方法,您不必調用A()
方法即可填充要在B()
使用的值
如果您正在使用的類的同一個實例的工作Test
,價值a
和b
在方法中設置A()
應該還是在方法可見B()
因此,以下將起作用:
Test test = new Test();
test.A();
test.B();
但是,以下內容不會
new Test().A();
new Test().B();
附帶說明一下,Java中的方法應始終以小寫字母開頭,並使用camelcase。
如果您要獲取a和b的當前(最新)值,則可以編寫2種方法,例如
public int getA() {
return currentMenu.getCurrentFocusedItem().getItemID();
}
public int getB() {
return currentMenu.getMenuID();
}
並使用這些方法代替調用A()更新a,b的值,然后在方法B中再次訪問它們。
你也可以嘗試
public void A()
{
a = currentMenu.getCurrentFocusedItem().getItemID();
b = currentMenu.getMenuID();
System.out.println("Inside A ()" + a + " &&" + b);
}
public void B()
{
Test test=new Test();
test.A(); // assign values for a and b
System.out.println("Inside B ()" + a + " &&" + b);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.