0

Anyone can explain this code

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); } } public class Person { private String name; private int age; Person (String n) { this.name = n; } public int getAge() { return age; } public void setAge(int a) { this.age = a; } }

13th Sep 2018, 9:14 AM
Malak Layth Jamal
Malak Layth Jamal - avatar
3 Réponses
+ 2
It starts j as Person type. This is the class. j = new Person("John"); calls the constructor method (Person(String n)) passing a parameter "John" to it. The name of the object j (referenced by "this") gets the n value ("John"). setAge sets the age of j, this again references j, and sets the age attribute to the parameter it received. celebrateDay increases age by 1. j.getAge shows the parameter age to external classes. This is called encapsulation, what mean to make attributes not directly accessible to other classes, only by methods. This can look silly on basic programs, but helps you a lot on complex/huge ones.
13th Sep 2018, 9:41 AM
Alexander Santos
Alexander Santos - avatar
+ 2
You are welcome
13th Sep 2018, 11:29 AM
Alexander Santos
Alexander Santos - avatar
0
Alexander Santos hmmm thanks
13th Sep 2018, 9:47 AM
Malak Layth Jamal
Malak Layth Jamal - avatar