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

子类不应该继承total并将其设置为零吗?我做错了什么?我知道我可以把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;
}
}
}

除了在名称中指出的事情之外,比如不使用小写字母作为类名的开头;我认为它不起作用的原因是,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 

以下是您修改后的主要方法:


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

最新更新