首页 > 解决方案 > java扩展类继承

问题描述

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();
}

班级:

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

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

标签: javasubclass

解决方案


通过制作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;
        }
    }
}

推荐阅读