任何人都可以告诉我super关键字在这里有什么用? 我正在尝试使用继承进行代码加法操作,其中存在三个类,其中变量在一个类中声明,而实际的操作代码在另一类中,而主类在那里。
class Oper extends Variables {
void op() {
Scanner input = new Scanner(System.in);
System.out.println("Enter any two numbers: ");
super.input1 = input.nextInt();
super.input2 = input.nextInt();
result = input1 + input2;
System.out.println("Result = " + result);
}
}
class Variables {
int input1, input2, result;
}
class Addition {
public static void main(String[] args) {
Oper obj = new Oper();
obj.op();
}
}
答案 0 :(得分:1)
super在javadocs之后说:
如果您的方法覆盖其超类的方法之一,则可以 通过使用关键字super调用覆盖的方法。您 也可以使用super来引用隐藏字段(尽管隐藏字段 不鼓励)。
在您的示例中,超级引用了父class Variable
的属性。您可以忽略它,因为子类没有具有相同名称的属性。如果在Variable
类和Oper
类中具有相同的变量名称,则必须使用它来区分。
和大约input.nextInt()
:
在您的情况下,输入为System.in
,因此它是从系统输入中读取的,默认情况下,它是控制台输入。
nextInt()
正在读取字符并将其转换为int类型(more info)。
读取四个输入字节并返回一个int值