2015-11-14 97 views
-2

我對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; 
} 
+0

範圍不適用的對象。它適用於程序源代碼中的名稱。 –

+0

此外,'方法'執行完成後'i'被銷燬,所以無論如何您都無法訪問它。 –

+0

@SotiriosDelimanolis:那麼在我上面的例子中,我怎樣才能改變訪問類A中的方法中的B類成員? – user3618703

回答

0

您需要將B對象作爲參數的方法:

public void method(B example) 
{ 
int i = example.value; 
} 
public static void main(String args[]) 
{ 
    B example = new B(); 
    method(example); 
+0

我通過在方法調用之外聲明靜態對象來編輯上面的代碼。會造成什麼問題嗎?謝謝〜 – user3618703

+0

如果你在方法之外聲明它,但在同一個類中聲明它,你不需要在方法參數中傳遞它,但它應該一直工作。 Google Java成員變量。 – EkcenierK

相關問題