简体   繁体   English

如何从另一个类更新一个类中的变量

[英]How to update a variable in one class from another class

I realize this is probably a really basic question, but I can't figure it out. 我意识到这可能是一个非常基本的问题,但我无法弄清楚。

Say I have this main class 说我有这个主要课程

public class Main{

    public static void main(String[] args){
        int a = 0;
        AddSomething.addOne(a);
        System.out.println("Value of a is: "+String.valueOf(a));
    }
}

Here is AddSomething class and addOne() method 这是AddSomething类和addOne()方法

public class AddSomething{

    public static void addOne(int a){

        a++;

    }
}

The addOne method is not adding anything addOne方法没有添加任何内容

System.out.println("Value of a is: "+String.valueOf(a));
// Prints 0 not 1

How can I make Add class update variable a in Main class? 我怎样才能让Add类更新变量aMain类?

addOne receives a copy of a , so it can't change the a variable of your main method. addOne接收的拷贝a ,所以它不能改变a main方法的变量。

The only way to change that variable is to return a value from the method and assign it back to a : 改变该变量的唯一方法是从方法返回一个值,并将其分配回a

a = Add.addOne(a);

...

public int addOne(int a){
    return ++a;
}

Thats becouse primitive types in java pass to methods by value. 这就是因为java中的原始类型按值传递给方法。 Only one way to do what you want is reassign variable, like : 只有一种方法可以做你想要的是重新分配变量,例如:

public class Main{

    public static void main(String[] args){
        int a = 0;
        a = Add.addOne(a);
        System.out.println("Value of a is: "+String.valueOf(a));
    }
}

and

public class AddSomething{

    public static int addOne(int a){

    return a++;

    }
}

I know, Eran's answer is what you all need. 我知道,Eran的回答是你们所有人都需要的。 But just to show another way, posting this answer. 但只是为了表明另一种方式,发布这个答案。

public class Main
{
  static int a = 0;
  public static void main(String[] args)
  {
    AddSomething.addOne();
    System.out.println("Value of a is: "+a);
  }
}

And in AddSomething class.. AddSomething类中..

public class AddSomething
{
    public static void addOne(){ Main.a++ };
}

AddSomething must be in same package as Main class, as int a has default access modifier. AddSomething必须与Main类在同一个包中,因为int a具有默认访问修饰符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM