java - 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
主类,但我希望它在一个单独的类中。谢谢你的帮助。
解决方案
通过制作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;
}
}
}
推荐阅读
- java - ModelMapper 中的自定义转换器没有被触发
- redux - 如何通过 ID ngrx 获取实体
- php - 如何使用 SMTP 驱动程序在 laravel 中发送批量电子邮件而不创建多个 smtp 客户端/会话
- python-3.x - 等待分离的容器运行
- spring-cloud-config - Spring Cloud Config Basic Security 抛出 401 错误
- java - 依赖于一个模块,该模块具有传递依赖的配置文件
- selenium - 如何不为依赖于该背景场景的 Cucumber 功能不断重复背景场景
- android - 在颤动中滚动Gridview时项目消失
- javascript - 如何在 CDN 链接中使用 google API 密钥获取 json 格式以获取用户的当前地址?
- git - 我不小心将带有 google 密钥的 .env 文件上传到 github,但编辑了文件并删除了密钥。可以在某处看到变化吗?