How to initialise id in objects so that every new object has id 1 greater than prevs
Is it possible to initialise id in objects so that every new object has id 1 greater than previous object.
Id is like a variable in the class. So if the first object is formed id has value 550 for the first object. For the second object Id has value 551. third -552 and so on.
We cannot use static as the id becomes common to all the classes and it increases for each and every object.
Re: How to initialise id in objects so that every new object has id 1 greater than pr
Quote:
Originally Posted by
dayal.adi
We cannot use static as the id becomes common to all the classes and it increases for each and every object.
Yes but you could use two variables, one as a static variable (counter) and one for the id (object value)
Code:
class Foo{
private static int counter = 550;
private int id;
public Foo(){
this.id = counter++;
}
}
??
Re: How to initialise id in objects so that every new object has id 1 greater than pr
I wrote little program based on @eRaaaa's idea:
Code:
public class Foo {
private static int counter = 550;
private int id;
public Foo() {
this.id = counter++;
}
public int getId() {
return id;
}
public static void main(String[] args) {
Foo firstObject, secondObject, thirdObject;
firstObject = new Foo();
System.out.println("First object's id: " + firstObject.getId());
secondObject = new Foo();
System.out.println("Second object's id: " + secondObject.getId());
thirdObject = new Foo();
System.out.println("Third object's id: " + thirdObject.getId());
}
}