Wednesday, June 3, 2015

Static Variables


// Static variables belong to a class
// They are accessed using ClassName.variableName outside the class
// Only 1 single copy of a static variable is maintained across all objects
// Every method of a class can access a static variables including constructors
// class wide information common to every object should be static
// initial value for a static variable is given once when the program starts


// COUNT THE NO OF OBJECT CREATED
public class StaticVarsDemo1 {

public static void main(String[] args) {

ClasName cNam = new ClasName();
ClasName cNam2 = new ClasName();
ClasName cNam3 = new ClasName();

int n = ClasName.objNo;
System.out.println("\n"+n);
}
}

class ClasName{

static int objNo = 1000;
// if there is no static word here then all objects would have 1001 no.

public ClasName() {
objNo++;
System.out.println("Object no is: "+objNo);
}
}


No comments:

Post a Comment