I'm a bit confused
I created a class called person, that has an age and name attributes (and get set methods). Then in another class I want to create an array of persons , where each person has a different age and name. But some how in the end all of my persons end up with the last name and age. If I manually create them then it is ok, but with a for loop I've got that problem. What should I do to get different persons?
Here is the code of the person class:
public class person {
static String name;
static int age;
public person() {
name="name";
age=0;
}
public static String getName() {
return name;
}
public static void setName(String name) {
person.name = name;
}
public static int getAge() {
return age;
}
public static void setAge(int age) {
person.age = age;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
And here is the code where I want to create my array/matrix:
public class array {
static person[][] a;
public static void main(String[] args) {
a=new person[3][3];
//manual created person
person first=new person();
person second=new person();
person third=new person();
first.setAge(12);
first.setName("first");
second.setAge(20);
second.setName("second");
third.setAge(40);
third.setName("third");
//automatic (here I get the disired effect)
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
a[i][j]=new person();
a[i][j].setAge(10+j);
a[i][j].setName("Alia"+i);
System.out.println(i+" "+j+" "+a[i][j].getName()+" "+a[i][j].getAge());
}
}
// a[0][0]=first;
// a[0][1]=second;
// a[1][2]=third;
// System.out.println(a[0][0].getName()+" "+a[0][0].getAge());
//for checking , and it doesnt work anymore
System.out.println(a[0][0].getName()+" "+a[0][0].getAge());
// for (int i = 0; i < a.length; i++) {
// for (int j = 0; j < a.length; j++) {
// System.out.println(i+" "+j+" "+a[i][j].getName()+" "+a[i][j].getAge());
// }
//
// }
getname();
}
private static void getname() {
System.err.println("get name function");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
System.out.println(a[i][j].getName());
}
}
}
}