Объясните код и его результат | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Объясните код и его результат

public class MyClass { public static void main(String[ ] args) { Person j; j = new Person("John"); j.setAge(20); celebrateBirthday(j); System.out.println(j.getAge()); } static void celebrateBirthday(Person p) { p.setAge(p.getAge() + 1); } } //Outputs "21" Уважаемые, доступно(!) объясните блондинке, почему там ответ 21? p и j это одно и то же?

4th Oct 2017, 1:01 PM
Edelis
Edelis - avatar
2 Answers
+ 7
j у тебя класс, р - объект. Класс - формочка и рецепт печенья Объект - само печенье Ты работать можешь только с объектом (съесть, потрогать (и понять характеристики) сможешь только печенье), а класс - это описание твоего печенья (его формы, ингридиенты), с которого ты ничего не возьмешь, кроме как общей идеи о будущем печеньи.
4th Oct 2017, 2:12 PM
Tato
Tato - avatar
+ 7
j is a variable of Person class, a concrete object. It is declared to represent John and is assigned the age of 20. Now p is just a parameter used during celebrateBirthday method definition. It represents any parameter of a Person class used in this method. The flow is that in the main class you declare j to be John, aged 20 and execute the celebrateBirthday method on him (on j). What the method does, it increases the age parameter of any object passed to it - in your case it's j. Unfortunately, it happens to be John. He just got older and is 21 now :(
4th Oct 2017, 2:16 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar