【问题标题】:How do I acces attributes from an object, inside a List, in the same class?如何在同一个类中访问 List 内的对象的属性?
【发布时间】:2016-03-10 19:53:51
【问题描述】:

我想从对象初始化的类中访问对象的变量。我尝试过使用 objectName.atrr 并尝试过使用 get 方法。当我键入“testObject”时使用这两种方法。属性不会显示在可能性列表中,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

【问题讨论】:

    标签: java class object constructor attributes


    【解决方案1】:

    从使用泛型开始:

    List<State> listState = new ArrayList<>();
    

    然后将您的testObject 视为State 的实例,而不是Object

    State testObject = currentState.get(0);
    

    当您将testObject 声明为Object testObject = currentState.get(0); 时,您是在告诉编译器将testObject 作为Object 的实例来处理。它将无权访问State 的任何成员或方法。

    【讨论】:

    • testObject.sID 不是公开的,因此假设代码中的其他所有内容都有效,代码仍然会出错。
    • 谢谢!我尝试使用 State 但出现错误,因为我忘记将其设为 列表。这对我来说有点愚蠢;)。现在可以了!
    • @user2173361 如果答案有效,您应该将其标记为正确
    • 我必须等待 7 分钟才能点击正确的标志。现在我做对了吗?
    猜你喜欢
    • 2013-08-22
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    相关资源
    最近更新 更多