Reputation: 71
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?
Upvotes: 0
Views: 193
Reputation: 425198
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));
}
Upvotes: 1