简体   繁体   English

Getter 方法返回 0 值

[英]Getter method is returning 0 value

I'm creating a class MDA_EFSM and it has two variable int k and int[] listA and creating setter and getter methods to initialize these two variables.我正在创建一个类 MDA_EFSM,它有两个变量 int k 和 int[] listA 并创建 setter 和 getter 方法来初始化这两个变量。 Then I'm calling getter method of MDA_EFSM in another class.然后我在另一个类中调用 MDA_EFSM 的 getter 方法。 The getter method should return recently set value, but it is returning '0'. getter 方法应该返回最近设置的值,但它返回“0”。

public class MDA_EFSM {
    int k;
    public int listA[] = {0, 1};   

    public int getK() {
        return k;
    }
    public void setK(int k) {
        this.k = k;
    }

    public int[] getA() {
        return listA;
    }
}

public class State {
    MDA_EFSM mda = new MDA_EFSM();

    public void setMda(MDA_EFSM mdaefsm)
    {
        mda = mdaefsm;
    }
    public MDA_EFSM getMda() {
        return mda;
    }
}

public class S0 extends State{

    public void Insert_cups(int n){
        if (n > 0){
            int value = mda.getK();
        }
    }
}

I am setting value in one class and getting that value from another class.我在一个类中设置值并从另一个类中获取该值。 Here is the code snippet of that class:这是该类的代码片段:

public class S1 extends State{
    public void Insert(int n){
        if (n > 0){
            mda.setK(n);
        }
    }
}

I expect the output of recently set value, but getter method is returning '0'我希望输出最近设置的值,但 getter 方法返回“0”

You haven't set any value.您尚未设置任何值。 You got default value of int.你得到了 int 的默认值。 By the way I cannot see in code you set any value for int.顺便说一句,我在代码中看不到您为 int 设置了任何值。

Each of your class S0 and S1 has an own instance of MDA_EFSM (by the way you should read Java naming convention).您的每个类 S0 和 S1 都有自己的 MDA_EFSM 实例(顺便说一下,您应该阅读 Java 命名约定)。 You set the Value of k in S1 but read the value of another k in S0.您在 S1 中设置了 k 的值,但在 S0 中读取了另一个 k 的值。 To achieve what you want k hast to bee static.要实现你想要的 k 必须是静态的。

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

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