Hello there,
I have wrote the below code and its working perfectly,when i tried to add a static field (noOfPerson) to show me the number of persons that is created in the main class, i get a wrong number !
I would really appreciate it if you review my code for any error.
public class Person { private int age; private String name; private static int noOfPerson = 0; public Person(String a_name, int a_age){ setName(a_name); setAge(a_age); setNoOfPerson();} public Person(){ this("None", 1); setNoOfPerson(); } public Person(String a_name){ this(a_name, 1); setNoOfPerson(); } public Person(int a_age){ this("None",a_age); setNoOfPerson(); } public void setName(String a_name){ name = a_name; } public String getName(){ return name;} public void setAge(int a_age){ age = a_age; } public int getAge(){ return age;} public static void setNoOfPerson(){ Person.noOfPerson++; } public static int getNoOfPerson(){ return noOfPerson;} public String toString() { return String.format("%s is %d years old.", getName(), getAge()); } }
class including main method
public class Person_Test { public static void main (String[] args){ Person employ1 = new Person("Ahmad", 32); System.out.println(employ1.toString()); Person employ2 = new Person("Ali"); System.out.println(employ2.toString()); Person employ3 = new Person(28); System.out.println(employ3.toString()); Person employ4 = new Person(); System.out.println(employ4.toString()); System.out.println(Person.getNoOfPerson()); } }
here at the end its suppose to show me (Person.getNoOfPerson()) number 4 but im getting number 7!
Thanks in advance for your help.
Best Regards,