简体   繁体   中英

Edit class in an array [Java]

My current goal is to be able to have a given number of class variables, but i am having trouble editing the class once already created.

What i have currently:

List<Mammal> list = new ArrayList<Mammal>();
list.add(new TreeLemur());
list.set(i, TreeLemur.setAge(12));

Mammal is the parent function of Lemur, which is the parent function of TreeLemur. What im not sure about it how to run certain parts of that code, for example: TreeLemur.setAge(12);

I apologize for my broken English, any help would be greatly appreciated.

Why not set its age before adding it to the ArrayList:

List<Mammal> list = new ArrayList<>();
TreeLemur treeLemur = new TreeLemur();
treeLemur.setAge(12);
list.add(treeLemur);

首先,从位置获取元素,然后设置新值。

  list.get(i).setAge(12);

If I don't understand wrong, you want to modify the TreeLemur instance using its method, not Mammal's (eg, setAge of TreeLemur).

If so, you can do it as follow:

Mammal mammal = list.get(i);
if(mammal instanceof TreeLemur){
    TreeLemur lemur = (TreeLemur)mammal;
    lemur.setAge(12);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM