简体   繁体   中英

How to modify an object's private ArrayList attribute from another object (Java)

Let's say I have a class:

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)
}
}

and then before I talk more about the question I'll add the wound class to continue the example:

public class Wound
{
private int severity;

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

Now, in this case, I want to make a call for person1 to hit person2, adding a wound to person2's wounds ArrayList. Ex:

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

That code block above is the dream, where I call punch from the puncher with the person getting punched as the object being passed in as a parameter. Is this possible?

Since both objects are instances of the same class, person1 has access to all of person2's fields, so:

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

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