我想从对象被初始化的类中的对象中访问变量。我尝试使用objectName.atrr并尝试使用get方法。当我键入" testObject时,使用这两种方法。" atrributes不会显示在可能性列表中,get方法也不会显示为选项。 如何从同一类中的List内的对象访问属性?
public class State{
// This is the constuctor
Point sPos;
int sID;
int sRot;
List listState = new ArrayList();
public ClassName(Point shape_Pos, int shape_ID, int shape_Rot){
sPos = shape_Pos;
sID = shape_ID;
sRot = shape_Rot;
}
//here are the get methods
public int getID() {
return sID;
}
public Point getPos() {
return sPos;
}
public int getRot(){
return sRot;
}
public void methodName(){
//here is code that creates States and add it to listState (left it out)
currentState.add(new State(new Point(0,0),1,1));
...
Object testObject = currentState.get(0);
System.out.println("testObject = "+testObject);
//This is not working
int id = testObject.sID;
// This is also not working
int id2 = testObject.getID();
}
}
OUTPUT://就像我期望和想要的一样,与列表中的对象相同
Object = State@1ae73783
答案 0 :(得分:0)
首先使用泛型:
List<State> listState = new ArrayList<>();
然后将testObject
视为State
的实例,而不是Object
:
State testObject = currentState.get(0);
当您将testObject
声明为Object testObject = currentState.get(0);
时,您告诉编译器将testObject
作为Object
的实例处理。它无法访问State
的任何成员或方法。