How to check the accessibility of an instance variable by a static method in java

A static method belongs to the category instead of the thing of a category . It are often invoked without the necessity for creating an instance of a category . It can access static data member and may change the worth of it.

The static keyword may be a non – access modifier in Java which may be used for variables, methods, and block of code. Static variables in Java belong to the category i.e it's initialized just one occasion at the beginning of the execution. By using static variables one copy is shared among all the instances of the category and that they are often accessed directly by class name and don’t require any instance. The Static method similarly belongs to the category and not the instance and it can access only static variables but not non-static variables.

We cannot access non-static variables or instance variables inside a static method. Because a static method are often called even when no objects of the category are instantiated.

Example 1: 

// Java Program to Check the Accessibility
// of an Instance variable by a Static Method

import java.io.*;

class GFG {
	
	// Instance variable
	public int k = 10;

	public static void main(String[] args)
	{

		// try to access instance variable a
		// but it's give us error
		System.out.print("value of a is: " + k);
	}
}

Output :

prog.java:16: error: non-static variable k cannot be referenced from a static context
        System.out.print("value of a is: " + k);
                                             ^
1 error

Instance variables, as the name implies, we need an instance of a class. We cannot directly access instance variables from static methods. Therefore, to access instance variables, we must have an instance of the class from which instance variables can be accessed.

Example 2 :

// Java Program to check accessibility of
// instance variables by static method

import java.io.*;

class GFG {
	
	// instance variable
	public int k;

	// Constuctor to set value to instance variable
	public GFG(int k) { this.k = k; }
	
	// set method for instance variable
	public void setK() { this.k = k; }
	
	// get method for instance variable
	public int getK() { return k; }

	public static void main(String[] args)
	{

		// Calling class GFG where instance variable is
		// present
		GFG gfg = new GFG(10);

		// now we got instance of instance variable class
		// with help of this class we access instance
		// variable
		System.out.print("Value of k is: " + gfg.getK());
	}
}

Output

Value of k is: 10

 

Submit Your Programming Assignment Details