我對Java中的對象範圍有疑問。 例如,我有兩個稱爲A類和B類的類。主要方法在類A中,並且我在main()中實例化了一個B類對象。我發現我不能在A類的另一種方法中使用這個對象。爲什麼?如果我想在這個類的一個方法的另一個類中使用方法,我該怎麼做?Java - 在用同一類的另一種方法實例化的方法中使用對象
public class A
{
public static void method()
{
int i = example.value;
}
public static void main(String args[])
{
B example = new B();
method();
}
}
public class B
{
public int value = 3;
}
我可以這樣做嗎?
public class A
{
static B example;
public static void method()
{
int i = example.value;
}
public static void main(String args[])
{
example = new B();
method();
}
}
public class B
{
public int value = 3;
}
範圍不適用的對象。它適用於程序源代碼中的名稱。 –
此外,'方法'執行完成後'i'被銷燬,所以無論如何您都無法訪問它。 –
@SotiriosDelimanolis:那麼在我上面的例子中,我怎樣才能改變訪問類A中的方法中的B類成員? – user3618703