有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法理解为什么这个程序会给我这个输出。请给我解释一下

当我运行这个程序时,它会给我以下输出。为什么我得了2分而不是5分。那我为什么要得到这个输出呢?我没能理解。请给我解释一下

public class G {

   public  int x = 3; 
   public static int y = 7; 

   public static void main(String[] args) {

       G g = new G();
       G h = new G();

       g.x=1;
       g.y=5;
       h.x=4;
       h.y=2;

       System.out.println("g.x="+g.x);    
       System.out.println("g.y="+g.y);
       System.out.println("h.x="+h.x);
       System.out.println("h.y="+h.y);

    } 
}

输出:

g.x=1
g.y=2
h.x=4
h.y=2

共 (2) 个答案

  1. # 1 楼答案

    静态变量是每个类一个,而不是每个实例一个

    g.yh.y(和G.y)都引用同一个变量,因此最后一个赋值获胜,值为2

    通过类的实例访问static变量是令人困惑的,但Java允许这样做

  2. # 2 楼答案

    提示:尝试思考静态变量的用途和行为

    阅读this

    Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.