静态方法中的局部变量也是静态的吗? [英] Are local variables in static methods also static?

查看:389
本文介绍了静态方法中的局部变量也是静态的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果我们在静态方法中声明它们,所有局部变量都会变为静态吗?

I am wondering do all the local variables become static if we declare them in a static method ?

例如:

  public static void A(){
        int x [] = {3,2};
        changeX(x);

        for (int i = 0; i< x.length; i++){
             System.out.println(x[i]);   // this will print -1 and 1
        }
  }
  private static void changeX(int[] x){
        x[0] = -1;
        x[1] =  1;
  }

据我所知,Java总是按值传递,但为什么在我们进行changeX调用后,X的状态发生了变化?有人可以解释一下吗?任何人都可以解释Java如何在内存分配方面处理静态变量?如果我们将静态变量作为参数传递给函数会发生什么(我知道人们通常不这样做)

As far as I understand that Java is pass by value always, but why the state of X has changed after we made the changeX call ? Can anyone explain that please ? and can anyone explains how does Java deal with static variables in terms of memory allocation ? and what happen if we pass a static variable to a function as a parameter (I know people won't normally do that)

推荐答案

大多数问题的答案是与任何其他变量相同。

The answer to most of your questions is "the same as any other variable."

静态方法中的局部变量只是静态方法中的局部变量。它们不是静态的,它们在任何方面都不是特殊的。

Local variables in static methods are just local variables in a static method. They're not static, and they're not special in any way.

静态变量保存在附加到相应<$的内存中c $ c> Class 对象;静态引用变量引用的任何对象都只存在于常规堆中。

Static variables are held in memory attached to the corresponding Class objects; any objects referenced by static reference variables just live in the regular heap.

当您将静态变量作为参数传递给方法时......绝对没有任何有趣的事情发生。

When you pass a static variable to a method as an argument... absolutely nothing interesting happens.

关于代码中的方案:


  1. 想象一下,你在一个字符串上有一个玩具气球(气球是你的数组对象,字符串是在 A()中声明的引用。)

  2. 现在你将另一个字符串绑定到气球上​​并将该字符串交给朋友(这正是你在调用 changeX()时发生的事情方法:字符串是方法的参数,它指向同一个对象。)

  3. 接下来,你的朋友拉入字符串,带一个黑色标记,在气球上绘制一个面(这就像修改数组的 changeX()方法)。

  4. 然后你的朋友解开他的字符串,只留下你的绳子附在气球上(方法返回ns,以及中的局部变量changeX()超出范围。)

  5. 最后你卷入字符串并查看气球:当然,你看到了脸(你的 A()例程看到了更改过的数组。)

  1. Imagine that you have a toy balloon on a string (the balloon is your array object, and the string is the reference to it declared in A().)
  2. Now you tie another string on to the balloon and hand that string to a friend (that's exactly what happens when you call the changeX() method: the string is the parameter of the method, and it points to the same object.)
  3. Next, your friend pulls in the string, takes a black marker and draws a face on the balloon (this is like the changeX() method modifying the array).
  4. Then your friend unties his string, leaving just your string attached to the balloon (the method returns, and the local variable in changeX() goes out of scope.)
  5. Finally you reel in the string and look at the balloon: of course, you see the face (your A() routine sees the changed array.)

这真的很简单!

这篇关于静态方法中的局部变量也是静态的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆