I create a method that casts an aging spell upon people and decreses their age by two:
public class Wizard {
void agingSpell (Person x) {
x = new Person(x.age);
x.age -=2;
}
}
Here's the class describing those people:
public class Person {
int age;
int weight = 90;
String name = Max;
Person (int x){
this.age = x;
}
}
I create an instance of Person and Wizard:
Person max = new Person(26);
Wizard albus = new Wizard();
Then, I call the method agingSpell and source max as its argument:
albus.agingSpell(Person max);
Then, as I see it, the reference value inside max is assigned to x inside the method:
Person x = max;
Now we have one more reference to the created object. Next, a new object is created and (again, I might be wrong), is saved inside the x:
x = new Person(x.age)
I understand the old object to be substituted by the new one, so there has to be no trace of the old one inside the method. BUT, if I compile the code the age of the new object would also be 26 . Furthermor, I can easily access all the other fields of the older object (which was supposed to be unaccessible the moment we assigned his x reference to another object). I know I'm definitely missing something. Could you, please, help me figure it out?
Here's the executing portion of the code:
public class Wizard {
}
public static void main (String [] args){
Wizard albus = new Wizard();
Person max = new Person(26);
albus.agingSpell(max);
System.out.println(max.age);
}
}