Sunday, 9 February 2014

class variables

As we know, instance variables are associated with object, where as class variables associated with class, i.e, available for all objects.
    Syntax
         static dataType variableName;

    Example
        static int count;

static variables are accessed by using class name.

    Syntax to access static variable
        ClassName.variablename

Example : program to count number of objects created for a class 
class Person{
 static int count =0;
 
 Person(){
  count++;
 }
}

class PersonTest{
 public static void main(String args[]){
  Person personA = new Person();
  Person personB = new Person();
  System.out.println("Number Of persons created are " + Person.count);
 }
}


Output
Number Of persons created are 2


Constructors                                                 Static Metods                                                 Home

No comments:

Post a Comment