0
Can someone explain how this code works?
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"
3 Answers
+ 2
@ Carl
You could just assume the class exists. đ
@Main question
Objects are basically (Okay, yes @ran technically it's just the value of the reference đ) passed by reference.
Person is an Object.
So,
celibrateBirthDay(j);
Is passing the Object j as arguments.
static void celibrateBirthDay(Person p){}
This means that p will NOT be a new Person.
It will be the same Object as the one you passed through as arguments.
Example with arrays/
int[] myArray = {1,2,3}
doStuff(myArray);
System.out.println(myArray[0]);
static void doStuff(int[] a){
a[0] = 7;
}
Output: 7
This only works differently for primitive data-types, which are passed by value.
+ 1
It's a big no no.Java is passed by value!never pass by reference.The object is copy by reference,not pass by reference! Remember this!
0
Code won't work since there is no class called Person. Therefore you can't create an instance of Person.