Results 1 to 3 of 3
Like Tree2Likes
  • 2 Post By eRaaaa

Thread: How to initialise id in objects so that every new object has id 1 greater than prevs

  1. #1
    dayal.adi is offline Member
    Join Date
    Jul 2012
    Posts
    1
    Rep Power
    0

    Default 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.

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    6

    Default Re: How to initialise id in objects so that every new object has id 1 greater than pr

    Quote Originally Posted by dayal.adi View Post

    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)

    Java Code:
    class Foo{
    	private static int counter = 550;
    	private int id;
    	
    	public Foo(){
    		this.id = counter++;
    	}
    }
    ??
    awinston and kammce like this.

  3. #3
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default 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:

    Java 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());
    	}
    }

Similar Threads

  1. Replies: 9
    Last Post: 06-17-2012, 04:13 AM
  2. Greater Than the Average
    By jmscarlet9 in forum New To Java
    Replies: 44
    Last Post: 04-01-2012, 06:13 PM
  3. Replies: 0
    Last Post: 02-16-2012, 12:01 AM
  4. Help: 1 is greater than 3?
    By atac57 in forum New To Java
    Replies: 3
    Last Post: 01-08-2012, 04:00 AM
  5. Replies: 1
    Last Post: 05-04-2010, 11:00 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •