What is static? || What is static in java? || Types of static in java

 What is static:

When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.

In Java static is used in 3 ways:

1) Instance variables declared as static:

Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable.

Example:

class Student

{

int stuRollNo;

String stuName;

static int totalStudents = 0; //static variable

Student(int rollno, String name)

{

stuRollNo = rollno;

stuName = name;

totalStudents++;

}

void totalStudent()

{

System.out.println("Total Students Created :" + totalStudents);

}

}

class studentTest

{

public static void main(String args[])

{

Student st1 = new Student(1,"Ali");

Student st2 = new Student(2,"Junaid");

Student st3 = new Student(3,"M");

st1.totalStudent();

}

}

2) Methods declared as static:

Methods declared as static have several restrictions:

 They can only call other static methods.

 They must only access static data.

 They cannot refer to this or super in any way.

 It is illegal to refer to any instance variables inside of a static method.

The most common example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist.

3) Declare a static block:

You can declare a static block which gets executed exactly once, when the class is first loaded.

// Demonstrate static variables, methods, and blocks.

class UseStatic

{

static int a = 3;

static int b;

static void meth(int x)

{

System.out.println("x = " + x);

System.out.println("a = " + a);

System.out.println("b = " + b);

}

static { //static block

System.out.println("Static block initialized.");

b = a * 4;

}

public static void main(String args[]) {

meth(42);

}

}

You can call a static method of any class1 form any class2 by:

class class2Name {

class1Name.staticMethodName(); 

}

Post a Comment

Please do not enter any spam link in the comment box