Java Program to Check the Accessibility of an Instance variable by a Static Method
Last Updated :
18 Aug, 2021
A static method belongs to the class rather than the object of a class. It can be invoked without the need for creating an instance of a class. It can access static data member and can change the value of it.
The static keyword is a non – access modifier in Java which can be used for variables, methods, and block of code. Static variables in Java belong to the class i.e it is initialized only once at the start of the execution. By using static variables a single copy is shared among all the instances of the class, and they can be accessed directly by class name and don’t require any instance. The Static method similarly belongs to the class 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 can be called even when no objects of the class have been instantiated.
Example 1:
Java
import java.io.*;
class GFG {
public int k = 10 ;
public static void main(String[] args)
{
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
The instance variable, as the name suggests we need an instance of a class. We cannot access directly instance variables from a static method. Therefore, to access an instance variable, we must have an instance of the class from which we access the instance variable.
Example 2 :
Java
import java.io.*;
class GFG {
public int k;
public GFG( int k) { this .k = k; }
public void setK() { this .k = k; }
public int getK() { return k; }
public static void main(String[] args)
{
GFG gfg = new GFG( 10 );
System.out.print( "Value of k is: " + gfg.getK());
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...