1

I have this class

public class NInfo {
private  int val;
private static int indx=1;

public NInfo(int val) {
    this.val = val;
    this.indx++;
    }
}

I would like to auto increase the indx in every new object that I create starting 1 this code doesnt work , what shall I fix ?

Michal Borek
  • 4,584
  • 2
  • 30
  • 40
Tamir Moav
  • 21
  • 1
  • 4
  • 2
    This should work though, but you have to use `NInfo.indx++` instead of `this.indx++` (or even simply `indx++`). Side note: it's a matter of taste, but I would name the field `index` rather than `indx` (no need to remove the `e`). – sp00m May 26 '13 at 20:06
  • Make another variable `index` and set to it `this.indx++`. Static variable belongs to the class and not to the object. – Maroun May 26 '13 at 20:07
  • What do you think is hapenning here ? – Adarsh May 26 '13 at 20:07

4 Answers4

4

A static field is shared by every instance of the class. You need to store the value in a new field specific to the instance.

public class NInfo {
private  int val;
private int index;
private static int indx=1;

public NInfo(int val) {
    this.val = val;
    this.index = indx++;
    }
}

I would be interested in why you would like to add these indexes to each class.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1

Every object of a class has all the attributes and methods defined in a class except the static ones. The static variables and methods are not part of the instance of the class. this. operator is used to refer to the particular instance of the class. To refer to a static variable you need not instantiate the object. You can directly refer to the variable using ClassName.variableName . So every time you create a new instance of the variable in the code, indx is incremented (starting from 2 since you have post-incremented it).

In order to assign a new incremented value to an object, increment indx and assign it to a variable that is actually a part of the class instance(i.e. a variable that is not static).

Adarsh
  • 3,613
  • 2
  • 21
  • 37
0

You forgot the assignment operator operation.

NInfo.indx += 1;

EDIT:

public class NInfo {

  private int id;
  private int value;

  private static int index; // auto initialized to 0

  public NInfo(int value) {
    this.val = val;
    this.id = NInfo.index += 1;
  }

}
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
0

you should pass like an attribute the indx in the constructor, and increase the index where you create a

giacomotb
  • 607
  • 4
  • 10
  • 24