📜  Java程序通过静态方法检查实例变量的可访问性

📅  最后修改于: 2022-05-13 01:55:19.114000             🧑  作者: Mango

Java程序通过静态方法检查实例变量的可访问性

静态方法属于类而不是类的对象。无需创建类的实例即可调用它。它可以访问静态数据成员并可以更改它的值。

static 关键字是Java中的非访问修饰符,可用于变量、方法和代码块。 Java中的静态变量属于类,即它只在执行开始时初始化一次。通过使用静态变量,类的所有实例共享一个副本,并且可以通过类名直接访问它们,不需要任何实例。静态方法同样属于类而不属于实例,它只能访问静态变量而不能访问非静态变量。

我们不能在静态方法中访问非静态变量或实例变量。因为即使没有实例化类的对象,也可以调用静态方法。

示例 1:

Java
// 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);
    }
}


Java
// Java Program to check accessibility of
// instance variables by static method
 
import java.io.*;
 
class GFG {
   
    // instance variable
    public int k;
 
    // Constructor 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());
    }
}


输出 :

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

实例变量,顾名思义,我们需要一个类的实例。我们不能从静态方法直接访问实例变量。因此,要访问实例变量,我们必须有一个类的实例,从中可以访问实例变量。

示例 2:

Java

// Java Program to check accessibility of
// instance variables by static method
 
import java.io.*;
 
class GFG {
   
    // instance variable
    public int k;
 
    // Constructor 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());
    }
}


输出
Value of k is: 10