java - When and where are static variables/ methods useful? -


unless class private or part of java api, don't see using static advantageous part of oop.

the time see using static being useful when need object incrementer every time create new object of same type.

for example:

public class duck {     static int duckcount = 0;     private string name;  public duck(string name) {     this.name = name;     duckcount++;     } }  public class ducktesting { public static void main(string[] args) {     system.out.println(duck.duckcount);     duck 1 = new duck("barbie");     system.out.println(duck.duckcount);     duck 2 = new duck("ken");     system.out.println(duck.duckcount);   } } 

output:
0
1
2

update: useful answers found in java: when use static methods/variable

so here's little exemple : let's need create people profiles, we'll make class named profile , need every profile have id

public class profile{ int id; string name;  public profile(string name,int id) {this.name=name; this.id=id;} } 

the probleme here : how make default id , , every time create profile , increase , have it's own personal id ??like :

profile 1 :id=1 profile 2 : id=2  profile 3: id=3  

without creating manually !

to have need static variable ,it means variable shared objects same class : if variable equals 1 , means in others objects have same class have equals 1!

let's write our class have

public class profile{ int id; string name; //here it! first time have 1 static int idincreaser=1;   public profile(string name) {this.id=this.idincreaser; //so first time object have id=1 this.idincreaser++; //we'll increase next created object                      // have id=2 this.name=name; } } 

and static method, make static if use in main class or want same work our idincreaser


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -