簡體   English   中英

如果數據在同一包中,如何將數據從一個類傳遞到另一個類

[英]How to pass data from a class to another class if they are in the same package

我一直在做這個程序,我不得不將數據從一個類傳遞到另一個類,但是它們在同一個包中。 我應該怎么做?

實例化第二個類的構造函數中的第一個類,並像這樣使用它:

class DataSource{
   int x=2;
   //setter getter
}

class DataConsumer{
   DataConsumer(){
      DataSource d = new DataSource();
   }
   //use it then
   d.getX();
}

您需要在classB上定義一個對象,並使用setter和getter

例:

    class A{

    private int counter;

    public void setCounter(int c){
       this.counter = c;
    }
public int getCounter(){
   return c;
}

Class B{
private A myObject;
//constructor
B(){
    A a = new A(); // initialize A;
}
public void setValueInA(int val){
     a.setCounter(val); // here is the value "passed" to the class A

}

您可以創建兩個公共類A和B。然后,在B中實例化(創建實例)A,反之亦然。 現在,您有了另一個類的對象。 使用公共的setter和getter方法,您可以輕松地設置和獲取其他類的數據。

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM