Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 14th, 2012  |  syntax: None  |  size: 0.95 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How do I automacially assign a variable in constructor while creating objects
  2. final class Foo {
  3.   private static final AtomicInteger seed = new AtomicInteger();
  4.   private final int id;
  5.  
  6.   public Foo() {
  7.     this.id = seed.incrementAndGet();
  8.   }
  9. }
  10.        
  11. public class YourClass {
  12.     private static int generalIdCount = 0;
  13.     private int id;
  14.  
  15.     public YourClass() {
  16.         this.id = generalIdCount;
  17.         generalIdCount++;
  18.     }
  19. }
  20.        
  21. class Person {
  22.     private static int nextId = 1;
  23.     private final int id;
  24.  
  25.     Person() {
  26.         id = nextId++;
  27.     }
  28. }
  29.        
  30. public class Person {
  31.  
  32.     // same across all instances of this class
  33.     static int currentCounter = 0;
  34.  
  35.     // only for this instance
  36.     int personId;
  37.  
  38.     public Person(){
  39.         personId = currentCounter;
  40.         currentCounter++;
  41.     }
  42. }
  43.        
  44. public class Person{
  45.     public static int Increment = 1;
  46.  
  47.     public int ID;
  48.     public Person(){
  49.         this.ID = Increment;
  50.         Increment++;
  51.     }
  52. }