Results 1 to 4 of 4
Like Tree1Likes
  • 1 Post By DarrylBurke

Thread: Help with constructor counter.

  1. #1
    lannie1980 is offline Member
    Join Date
    Mar 2012
    Posts
    88
    Rep Power
    0

    Default Help with constructor counter.

    Hi,

    I've got a brain teaser here I think that I can't work out yet despite having spent a while on it lol.

    I have a class variable
    XML Code:
    private static int nextNumber = 1;
    and I have a constructor with this line in it

    XML Code:
    this.number = nextNumber++
    I need to set the number variable to the nextNumber value and then increment the value held by nextNumber by 1 so that it holds the number of the 'next' object to be created.

    The code I have does increment
    XML Code:
    this.number
    properly by 1 each time (this is normal)

    but, if I create 10 new objects the nextNumber variable has 10 as the value for every object instead of just 1 more than the number variable.

    This is driving me mad - please help ;)

    Regards

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,457
    Rep Power
    20

    Default Re: Help with constructor counter.

    A static variable/member belongs to the class, not to its instances.

    db
    Fubarable likes this.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: Help with constructor counter.

    nextNumber should == 10 for all, since it represents the next available number, not the number of the current instance. It is static and thus belongs to the class, not to the objects of the class.

  4. #4
    lannie1980 is offline Member
    Join Date
    Mar 2012
    Posts
    88
    Rep Power
    0

    Default Re: Help with constructor counter.

    Ok cool, thanks db and fubarable for the replies.

Similar Threads

  1. Replies: 5
    Last Post: 12-14-2011, 02:47 PM
  2. Counter
    By ks1615 in forum New To Java
    Replies: 6
    Last Post: 02-20-2009, 04:02 AM
  3. Frequency Counter
    By justlearning in forum New To Java
    Replies: 0
    Last Post: 05-07-2008, 11:50 PM
  4. Replies: 0
    Last Post: 12-19-2007, 10:10 AM
  5. Replies: 0
    Last Post: 12-19-2007, 10:01 AM

Tags for this Thread

Posting Permissions

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