> STATIC <

WHAT IS STATIC ;

> A like as, it can be accessed before any objects of its class are created, and without reference to any object.

STATIC VARIABLE ;

  • We can create static variables at the class level only.
  • static block and static variables are executed in the order they are present in a program.

. Static variables are, essentially, global variables.

STATIC METHOD ;

. The most common example of a static method is the main( ) method.

. Any static member can be accessed before any objects of its class are created.

. And without reference to any object.

. Methods declared as static have several restrictions.

. They can only directly call other static methods.


. They can only directly access static data.

STATIC VARIABLE AND METHOD ;

. Use the static variable for the property that is common to all objects.

. . Exp, in class Student, all students share the same college name.

. Use static methods for changing static variables.

PROGRAM ;

class Student {

String name;

int RollNo;



// static variable

static String clgName;



static int counter = 0;



public Student(String name)

{

this.name = name;



this.rollNo = setRollNo();

}


static int setRollNo()

{

counter++;

return counter;

}



// static method

static void setClg(String name) { clgName = name; }


void getStudentInfo()

{

System.out.println(“name : ” + this.name);

System.out.println(“rollNo : ” + this.rollNo);



// static variable

System.out.println(“cllgName : ” + cllgName);

}
}


public class StaticDemo {

public static void main(String[] args)

{

Student.setCllg(“Dhanalakshmi Srinivasan”);



Student s1 = new Student(“surya”);

Student s2 = new Student(“mani”);



s1.getStudentInfo();

s2.getStudentInfo();

}

}

Leave a Comment