Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem in incrementing

 
saad shaukat
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a class Delivery. This class have DeliveryID. What I want is that when user create instance of delivery the id should be incremented itself. I am writing following code but it doesnt work. Plz fix this.


publc class Delivery{

private int DeliveryID = 1;

public Delivery{

DeliveryID++;
}
}

What i am trying to do is that when first object is created id should be 1 but when second object is created its id should be 2 and so on. Plz help me with this.

thanks.
 
Ray Stojonic
Ranch Hand
Posts: 326
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
private int DeliveryID = 1; creates an instance variable, what you want is a class variable.

Plz fix it yourself
[ March 04, 2005: Message edited by: Ray Stojonic ]
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'll need to have both a class (static) field and the instance field you already have. The static field will track the highest ID assigned so far while the instance field will hold the ID for each Delivery. In the constructor, you want to increment the shared ID and assign it to the instance member (or assign first to start from 1).

Also, the Java convention is for methods (except constructor) and variables to start with a lowercase letter and uppercase the first letter of each additional word -- justLikeThis.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic