Friday, July 10, 2009

Easy way to study JAVA :: Static


-Static variable :: can be access without creating any object. There is only one copy of static variable in the class and every object of that class access this Static variable

-Static method :: is a method which accepts arguments instead of using instance variables.The opposite of a static method is an instance method.The default for a method is to be an instance method. Methods must be explicitly defined as static methods.A static method is also refer to as a class method.

Example1 ::

Class Demo {

int i=10 //instant variable

static int a=50;

public static void display(){

System.out.println(“display method”);

}

public static void main(String arg[]){

System.out.println(a); //directly call the variable

display(); //directly calles function

Demo d = new Demo();

System.out.println(d.a); //called by object

System.out.println(d.display()); //calles by object.

}

}


Example2 ::


class Ax {

int a;

Static int s;

public static void main(String arg[]) {

Ax a1 = new Ax();

a1.a++;

a1.s++;

System.out.println(a1.a);

Ax a2 = new Ax();

System.out.println(a2.a);

System.out.println(a2.s);

}

}

output

1

1

0

1



0 comments:

Post a Comment