0

Didn't get how this work

static void celebrateBirthday(Person p) { p.setAge(p.getAge() + 1); I didn't understand this part in the program & how it increased the age to 21 from 20 https://code.sololearn.com/cAydJ47Ifw94/?ref=app

29th Apr 2020, 11:11 AM
Aakash Kumar
Aakash Kumar - avatar
2 Réponses
+ 5
Basically you access the age attribute and you add one, before setting that as the new age.
29th Apr 2020, 11:13 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 1
celebrateBirthday(j); // You are passing a reference to the above method which in turn creates a new reference variable 'p' pointing to the same object. So now both 'j' and 'p' are pointing to the same object, any one of the reference can be used to modify the object attributes or behavior. p.setAge(p.getAge() + 1); Here p.getAge() will be 20 then you add 1 to it so it becomes 21. Now p.setAge(21); Now when you call j.getAge() it will return 21.
29th Apr 2020, 12:04 PM
Avinesh
Avinesh - avatar