java 扩展 class 继承

java extended class inheritance

Sum s = new Sum();
Sum.SetToZero z = new Sum.SetToZero();

Scanner input = new Scanner(System.in);
String read = input.nextLine();

while (!read.equals("end")) {

    if (read.equals("add")) {
        s.add()
    } 
    else if (read.equals("get")) {
        System.out.println(s.returnTotal());
    }
    else if (read.equals("zero")) {
        z.zero();
    }

   read = input.nextLine();
}

class:

public class Sum {

    int total = 0;

    public void add() {
        total += 1;
    }

    public int returnTotal() {
        return total;
    }

    public static class SetToZero extends Sum {

        public void  zero() {
            total = 0;
        }
    }
}

输入:

add
add
zero
add
get
add
get
end

输出:

3
4

需要输出:

1
2

子class不应该继承总数并设置为零吗?我究竟做错了什么?我知道我可以将 zero 移到主 class 中,但我希望它位于单独的 class 中。谢谢你的帮助。

通过将 total 变量设置为 static,您可以获得所需的输出。

class Sum {
    static int total = 0;
    public void add() {
        total += 1;
    }

    public int returnTotal() {
        return total;
    }

    public static class SetToZero extends Sum {
        public void  zero() {
            total = 0;
        }
    }
}

除了名字中指出的事情,例如不使用小写字母作为您的 class 名字的开头;我认为它不起作用的原因是因为您为 SumSum.SetToZero 使用了两个不同的变量实例。您不需要创建新变量,因为 SetToZero 具有 Sum 的所有属性。我认为你应该改变这个:

Sum s = new Sum();
Sum.SetToZero z = new Sum.SetToZero();
Sum.SetToZero s = new Sum.SetToZero(); // use s for all operations 

修改后的 main 方法如下所示:


public static void main(String[] args) {
    Sum.SetToZero s = new Sum.SetToZero();

    Scanner input = new Scanner(System.in);
    String read = input.nextLine();

    while (!read.equals("end")) {

        if (read.equals("add")) {
            s.add();
        } 
        else if (read.equals("get")) {
            System.out.println(s.get());
        }
        else if (read.equals("zero")) {
            s.zero();
        }

        read = input.nextLine();
    }
}

当我运行这个时,我看到了预期的输出:

src : $ java Sum
add
add
zero
add
get
1
add
get
2
end