JAVA - How To Create A Counter For Object In Java

JAVA - How To Create A Counter For Object In Java

__________________________________________________________________________

In This Java Code We Will See How To For Objects Created In Java Programming Language.

package javadb_001;


public class User{
    private int id;
    private String fname;
    private String lname;
    private int age;

    private static int pos = 0;//Counter 

    public User (){pos++;}//increment the counter in empty constructeur

    public User (int _id,String _fname,String _lname,int _age){
        this.id = _id;
        this.fname = _fname;
        this.lname = _lname;
        this.age = _age; 
        pos++;//increment the counter in constructeur with values
    }
    
    public int getId(){
     return this.id;
    }
    public void setId(int id){
        this.id = id;
    }
    
    public String getFname(){
        return this.fname;
    }
    
    public void setFname(String fname){
     this.fname = fname;    
    }
    
    public String getLname(){
        return this.lname;
    }
    
    public void setLname(String lname){
        this.lname = lname;
    }
    
    public int getAge(){
        return this.age;
    }
    
    public void setAge(int age){
        this.age = age;
    }

    public String showInfo(){
        return this.id+" - "+this.fname+" - "+this.lname+" - "+this.age;
    }
    
      public static void main(String[] args){
          
          User u1 = new User();
          User u2 = new User();
          User u3 = new User();
          User u4 = new User();
          User u5 = new User();
          User u6 = new User(1,"A1","B1",10);
          User u7 = new User(2,"A2","B2",20);
          User u8 = new User(3,"A3","B3",30);
          User u9 = new User(4,"A4","B4",40);
          System.out.println(pos);
      }
}


/////////////////////////////////////////OUTPUT:  9




Share this

Related Posts

Previous
Next Post »