A Static Data Field Can Be Accessed From Any Method in the Same Class.

The static keyword in Java is mainly used for retentiveness management. The static keyword in Java is used to share the aforementioned variable or method of a given course. The users tin apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the course than an example of the class. The static keyword is used for a constant variable or a method that is the same for every instance of a class.

The static keyword is a not-access modifier in Coffee that is applicable for the post-obit:

  1. Blocks
  2. Variables
  3. Methods
  4. Classes

Note: To create a static member(block, variable, method, nested grade), precede its declaration with the keyword static.

When a fellow member is declared static, it can be accessed earlier whatsoever objects of its form are created, and without reference to any object. For example, in the below java programme, we are accessing static method m1() without creating any object of the Exam grade.

Java

class Exam

{

static void m1()

{

System.out.println( "from m1" );

}

public static void primary(String[] args)

{

m1();

}

}

Static blocks

If you need to do the computation in order to initialize your static variables, yous tin declare a static block that gets executed exactly in one case, when the class is first loaded.

Consider the post-obit coffee program demonstrating the use of static blocks.

Java

class Test

{

static int a = x ;

static int b;

static {

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

b = a * 4 ;

}

public static void main(String[] args)

{

System.out.println( "from main" );

System.out.println( "Value of a : " +a);

System.out.println( "Value of b : " +b);

}

}

Output

Static block initialized. from master Value of a : 10 Value of b : 40

For a detailed article on static blocks, run across static blocks

Static variables

When a variable is declared every bit static, and then a unmarried copy of the variable is created and shared among all objects at the class level. Static variables are, substantially, global variables. All instances of the class share the aforementioned static variable.

Important points for static variables:

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

Beneath is the Java program to demonstrate that static block and static variables are executed in the guild they are present in a program.

Java

class Examination

{

static int a = m1();

static {

System.out.println( "Within static cake" );

}

static int m1() {

System.out.println( "from m1" );

return twenty ;

}

public static void main(String[] args)

{

Arrangement.out.println( "Value of a : " +a);

Arrangement.out.println( "from master" );

}

}

Output

from m1 Within static block Value of a : 20 from main

Static methods

When a method is alleged with the static keyword, it is known as the static method. The most mutual example of a static method is the master( ) method. As discussed above, Any static member tin exist accessed before any objects of its class are created, and without reference to any object. Methods alleged equally static have several restrictions:

  • They tin can only straight call other static methods.
  • They can only directly access static data.
  • They cannot refer to this or super in whatsoever way.

Beneath is the java program to demonstrate restrictions on static methods.

Java

class Exam

{

static int a = 10 ;

int b = 20 ;

static void m1()

{

a = twenty ;

System.out.println( "from m1" );

b = 10 ;

m2();

System.out.println( super .a);

}

void m2()

{

System.out.println( "from m2" );

}

public static void chief(Cord[] args)

{

}

}

Output:

prog.java:18: fault: non-static variable b cannot be referenced from a static context          b = x; // compilation error          ^ prog.java:22: error: non-static method m2() cannot exist referenced from a static context          m2();  // compilation error          ^ prog.java:25: mistake: non-static variable super cannot be referenced from a static context          Arrangement.out.println(super.a); // compiler error                              ^ prog.java:25: error: cannot notice symbol          System.out.println(super.a); // compiler fault                                   ^   symbol: variable a four errors

When to employ static variables and methods?

Use the static variable for the property that is common to all objects. For example, in class Student, all students share the same college name. Use static methods for irresolute static variables.

Consider the following java program, that illustrates the utilise of static keywords with variables and methods.

Java

grade Student {

String name;

int rollNo;

static String cllgName;

static int counter = 0 ;

public Student(Cord name)

{

this .name = name;

this .rollNo = setRollNo();

}

static int setRollNo()

{

counter++;

return counter;

}

static void setCllg(String proper name) { cllgName = name; }

void getStudentInfo()

{

System.out.println( "name : " + this .name);

System.out.println( "rollNo : " + this .rollNo);

Organization.out.println( "cllgName : " + cllgName);

}

}

public grade StaticDemo {

public static void chief(String[] args)

{

Student.setCllg( "XYZ" );

Student s1 = new Educatee( "Alice" );

Pupil s2 = new Student( "Bob" );

s1.getStudentInfo();

s2.getStudentInfo();

}

}

Output

name : Alice rollNo : 1 cllgName : XYZ name : Bob rollNo : two cllgName : XYZ

d

Static Classes

A class can be madestatic merely if it is a nested form. Nosotros cannot declare a top-level grade with a static modifier but can declare nested classes as static. Such types of classes are chosen Nested static classes. Nested static class doesn't demand a reference of Outer class. In this case, a static class cannot access non-static members of the Outer course.

Note: For static nested form, see a static nested class in java

Implementation:

Coffee

import java.io.*;

public course GFG {

private static String str = "GeeksforGeeks" ;

static course MyNestedClass {

public void disp(){

System.out.println(str);

}

}

public static void main(String args[])

{

GFG.MyNestedClass obj

= new GFG.MyNestedClass();

obj.disp();

}

}

This commodity is contributed past Gaurav Miglani. If you similar GeeksforGeeks and would similar to contribute, yous can also write an article using write.geeksforgeeks.org or mail your article to review-squad@geeksforgeeks.org. Encounter your article actualization on the GeeksforGeeks master folio and help other Geeks. Delight write comments if y'all find anything incorrect, or you want to share more than information virtually the topic discussed above.


whiteheadpailikey.blogspot.com

Source: https://www.geeksforgeeks.org/static-keyword-java/

0 Response to "A Static Data Field Can Be Accessed From Any Method in the Same Class."

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel