0

I have a class called Person which is like the following:

public class Person
{
    public static String name;
    public static int regNumber;

    public   String getName() {
       return name;
    }

    public  int getRegNumber() {
       return regNumber;
    }

    public Person(int x) {

       this.name = n;
       this.regNumber = x;
    }
}

I use this class to fill an array with students:

public class PeopleArray
{
    public static void main(String[]args) {

        Person [] students = new Person[3];
        int reg = 1;
        for (int i = 0; i<students.length; i++) {

           students[i] = new Person(reg++);

        }

        for (Person stu: students) {
           System.out.println(stu.getRegNumber());
        }

     }
}

The problem is that when I try to print out the ages of each individual person it seem that the array was filled with only the last object created by the Person class, because the only number that is printed is the number 2.

What am I doing wrong?

2
  • 10
    Remove the static modifier from your fields. And look up its meaning. Commented Oct 18, 2013 at 13:54
  • 4
    This compiles? What about this.name = n; ? Commented Oct 18, 2013 at 13:55

4 Answers 4

5

The fields name and regNumber are static, which means they do not belong to any particular instance, but rather to the class as a whole. All you need to do is remove the static keyword from the field declarations in Person, making them instance variables instead of class variables.

I also suggest you read Understanding Instance and Class Members.

Sign up to request clarification or add additional context in comments.

Comments

3

Try re-reading your Person field declaration:

public static String name;
public static int regNumber;

You have used static members, if you remove this keyword, it should start working.

Comments

0

You need to remove static from the Your instance variables. if you used static in instance variables then last modified value is present in the name and regNumber.

public class Person{
    public String name;
    public int regNumber;

}

Comments

0

Constructor in Person class assign a variable 'n' to the name. But you haven't defined it anywhere. Other than that, remove 'static' keyword from your variables.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.