Java:修改不带参数的变量

时间:2011-09-01 12:16:20

标签: java class methods scope call

我刚刚开始学习Java,我对学习Java的范围规则感到非常沮丧。您看到我希望在不使用参数/参数的情况下创建方法。

在JavaScript中,我可以轻松使用函数来完成此任务:

/** Function to increase 2 vars.
/** **/
function modifyNow(){
 a++;
 b++;
} // END

var a = 5;
var b = 10;

modifyNow();
// By this part, a and b would be 6 and 11, respectively.

现在这节省了我很多时间和简单,因为每当调用函数时,var a和b已经存在。

那么,有没有办法在Java中执行此操作而不需要像我在JavaScript中这样做的参数?或者还有另一种解决方法吗?

谢谢,谢谢你的帮助... ^^

6 个答案:

答案 0 :(得分:3)

在您的班级中将ab作为私有变量,并在modifyNow()中增加它们会有什么问题?顺便说一句,Java中的所有内容都必须位于中。你不能让全局代码徘徊......

答案 1 :(得分:2)

您可以为类字段而不是局部变量执行此操作。

class Clazz {

    int a = 5;
    int b = 10;

    public void modifyNow() {
        a++;
        b++;
    }
}

// ...

Clazz c = new Clazz();
c.modifyNow();

现在,每次调用modifyNow后,字段都会更新。

答案 2 :(得分:1)

全局变量很糟糕。如果不知道你的意图,我会说你需要将变量作为成员添加到你的班级。然后可以从任何成员函数访问它们。

答案 3 :(得分:1)

  

您看到我希望在不使用的情况下创建方法   参数/参数。

最好的答案是:不要!

如果您仍然想要这样,请查找公共静态变量。

答案 4 :(得分:1)

class Foo {

  int a = 5;
  int b = 10;

  public void modifyNow(){
    a++;
    b++;
  }

}

答案 5 :(得分:0)

您需要使用所谓的member变量,它们与您班级的instance相关联。

public class MyClass
{ 

  // these are Class variables, they are tied to the Class
  // and shared by all instances of the class.
  // They are referenced like MyClass.X
  // By convention all static variables are all UPPER_CASE
  private static int X;
  private static int Y

  // these are instance variables that are tied to 
  // instances of the class
  private int a;
  private int b;

  /** this the default no arg constructor */
  public MyClass() { this.a = 5; this.b = 10; }

  /** this is a Constructor that lets you set the starting values
      for each instance */
  public MyClass(final int a, final int b) { this.a = a; this.b = b; }

  public modifyNow() { this.a++; this.b++; }

  /** this is an accessor to retrieve the value of a */
  public int getA() { return this.a; }

  public int getB() { return this.b; }
 }

 final MyClass myInstanceA = new MyClass();
 myInstance.modifyNow();
 // a = 6, b = 11

 final MyClass myInstanceB = new MyClass(1, 2);
 myInstance.modifyNow();
 // a = 2, b = 3

每当您执行new MyClass()时,您将获得与instance不同的MyClass新独立instance

正如您所知,JavaScript无论如何都与Java无关。出于营销原因,他们选择了这个名字,这是一个可怕的讽刺。