Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi! Could you please explain me why is these answers? (Java) Thank you! 1. class

ID: 3672619 • Letter: H

Question

Hi!

Could you please explain me why is these answers? (Java)

Thank you!

1. class Person{
2. Person(String s,int i ){
3. ++pid;
4. name=s;
5. age=i;
6. }
7. static int pid;
8. int age;
9. String name;
10. }
11. class Test{
12. public static void main(String args[]){
13. Person p1 = new Person("John" , 22);
14. Test te = new Test();
15. Person p2 = te.change(p1);
16. System.out.println(p2.pid +" "+p2.name+ " "+p2.age);
17. System.out.print(p1.pid +" "+p1.name+" "+ p1.age);
18. }
19. private Person change(Object o){
20. Person p2 = (Person)o;
21. p2.age = 25;
22. return p2;
23. }
24. }

Answer: 1 John 25
1 John 25

Explanation / Answer

class Person{   //Person Class.
Person(String s,int i ){   //Person constructor.
++pid;                   //pid is a static variable, and will be incremented, everytime, the person object is created.
name=s;                   //The given string s, is initialized to name.
age=i;                   //The given integer i, is initialized to age.
}
static int pid;           //pid is a static variable, and therefore will be initialized to 0.
int age;                   //age is a private integer variable.
String name;               //name is a private string variable.
}
class Test{               //Test Class.
public static void main(String args[]){   //main method.
Person p1 = new Person("John" , 22);       //p1 is an object of type Person. Therefore, the members will be assigned with values:
                                            //p1.pid = 1. p1.name = John. p1.age = 22.
Test te = new Test();                   //te is an object of type Test.
Person p2 = te.change(p1);               //p2 is an object of type Person. But will be initialized with the method change().
                                            //Therefore, p2.pid = 2. p2.name = John. p2.age = 25.
System.out.println(p2.pid +" "+p2.name+ " "+p2.age);   //Prints the value of Object p2. So, 1, John, 25.
System.out.print(p1.pid +" "+p1.name+" "+ p1.age);   //Prints the value of Object p1. So, 1, John, 25.
}
private Person change(Object o){           //This is a private method of Test class, and will return the object of type Person.
Person p2 = (Person)o;                       //This function receives an object o, and will initialize the values to p2. So, p2 will now have the values same as p1 has. Ofcourse it points to the object it received, i.e., p1.
p2.age = 25;                               //It will update the value of age to 25. This means, it will update the value of p2.age, i.e., to which p2 is pointing to.
return p2;
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote