2011-04-12 127 views
0

我试图访问对象“其他”中的数组,但我无法弄清楚如何访问该变量。这是我到目前为止有:访问同一类别的另一个对象中的变量

public void union(DataSet other) 
{ 
    DataSet temp = new newdataexp(); 
    temp = other; 
} 

我一直无法弄清楚如何访问变量,甚至当我创建一个返回变量的类中的方法,然后试图从调用它这种方法结合。

我有这个方法,并试图做:String [] [] temp = other.getdata(),但编译器说它找不到符号:方法getdata()。

公共字符串[] []的GetData() {

返回FILEDATA;

}

+0

请阅读[块ANS声明】(http://java.sun.com/docs/books/jls/third_edition/html/statements.html) – 2011-04-12 18:43:23

+0

创建返回它应该有工作的方法。你应该发布了这个尝试,然后我们可以解释为什么它不起作用。 – 2011-04-12 18:49:51

+0

当我试图使用返回变量的方法时,我得到错误:无法找到符号方法数据()。 – john 2011-04-12 18:56:09

回答

0

我不知道我好明白你的问题,但在同一类的另一个目的是访问变量只是试试这个:

class MyClass { 
    private int[] myArray = new int[10]; 

    public void myMethod(MyClass myClass) { 
     // you can in this way: 
     // int[] tempArray = myClass.myArray 
     // but this is better: 
     int[] tempArray = myClass.getMyArray(); 
    } 

    public int[] getMyArray() { 
     return myArray; 
    } 

} 

编辑:

但是如果你想让联合更好的提取联合方法以外的类,创建方法:

public static MyObject union(MyObject myObjectFirst, MyObject myObjectSecond) { 
    ... 
} 
+1

这很让人困惑,因为你正在创建一个对象并将其称为“myClass”。初学者经常会将类和对象混淆在一起,所以我会避免在初学者的代码示例中这样做。 – 2011-04-12 18:47:35

+0

public String [] [] data(){ return this.filedata; }就是我所拥有的,我想这只会从我想要的类对象中返回变量。但是,它不起作用。 – john 2011-04-12 18:53:36

+0

@John我猜这是因为你在newdataexp类中有getdata方法,但是你在参数的方法中引用了DataSet(注意:DataSet中没有这种方法)。 – smas 2011-04-12 19:06:40

0

用方法返回的字符串,int等替换数据类型。

datatype mynewdata = (datatype)other.getMeMyArray();