/* related posts with thumb nails */

static members:

Static members include static data-members and static methods. These members are declared with the keyword “static”. These are often referred to as class variables and class methods.

STATIC DATA MEMBER (CLASS VARIABLES):

· Class variables are global to a class and belong to the entire set of objects that class creates. Only one memory location is created for each class variable. These are basically static data members of a class. They take common value for all the objects.

· When all objects of a class have common value for a data member, we write that data member as “static” and give the value once. Otherwise for each object, we need to assign data.

· Even if the class is not instantiated, java creates one copy of the static variable present in our class.

· Objects are insignificant with static data members.

· We can access public static data members using class name itself i.e. without taking any instances of that class i.e using the syntax: class-name.static-data-member-name

Example: class alpha

{

static int count=0;

alpha()

{

count++;

System.out.println(”Object ” + count + “ created”);

}

}

class Test

{

public static void main(String as[])

{

alpha a1=new alpha();

alpha a2= new alpha();

}

}

The above program prints “Object 1 created” “Object 2 created”

Explanation:

In the above program, we have taken a static data member by name “count” which is common for all the objects. The statement “static int count=0;” initializes its value to “zero”. As we have written a constructor, it is called when a1, a2 are created and “count” value becomes 1 and 2 respectively i.e. the count value gets incremented each time an object is created.

STATIC METHODS:

· Static methods are the methods which behave same for all the objects of a class.

· Objects are not needed to call static methods.

· Objects are insignificant with static methods

· We can invoke static methods using class name itself i.e. without taking any instances of that class

· Static methods can only call other static methods and refer to only static data members but they cannot access instance variables.

· They cannot refer to this or super in anyway.

Example:

class math

{

public static int fact(int n)

{

int f=1;

for(int i=1; i<=n ; i++)

f=f*i;

return f;

}

}

class Test

{

public static void main(String as[])

{

System.out.println(“Factorial of 4=”+math.fact(4));

}

}

Explanation:

In the above example, there is a static method “fact()”. When it is called, we’ve used as “math.fact()”as it is not necessary to create any objects to call static methods. We can also call it with the objects but it is meaningless to call with objects when the methods produce same result for all objects.

Related Topics:

0 comments:

Post a Comment