【问题标题】:How to modify an object's private ArrayList attribute from another object (Java)如何从另一个对象(Java)修改对象的私有 ArrayList 属性
【发布时间】:2021-05-08 07:57:05
【问题描述】:

假设我有一堂课:

public class Person
{
private int power;
private ArrayList<Wound> wounds;
//we will get to the wound class later, don't worry

//basic constructor
public Person(){
power = 10;
}

public void Punch(){
//here is where I am lost (void doesn't have to be void, just what I have for the example)
}
}

然后在我讨论更多问题之前,我将添加伤口类以继续示例:

public class Wound
{
private int severity;

//basic constructor
public Wound(int sev){
severity = sev;
}
}

现在,在这种情况下,我想调用 person1 来打击 person2,在 person2 的伤口 ArrayList 中添加一个伤口。例如:

class Main {
public static void main(String[] args) {
Person person1 = new Person();
Person person2 = new Person();
person1.punch(person2);
}
}

上面的代码块是梦境,我从打孔器中调用打孔器,将被打孔的人作为作为参数传入的对象。这可能吗?

【问题讨论】:

  • person1.punch(person2) - 您的代码中不存在这样的方法。 puncher 是谁重要吗?如果您想对person2's 伤口采取行动,那么punch 应该只对Person2's wound 字段采取行动。

标签: java class arraylist


【解决方案1】:

由于两个对象都是同一个类的实例,所以 person1 可以访问 person2 的所有字段,所以:

public void punch(Person victim){
    victim.wounds.add(new Wound(power));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 2020-11-06
    • 2020-11-21
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    相关资源
    最近更新 更多