/**定义一个父类Base中的方法calculate(),该方法用于计算两个数的乘积(X*Y)。定义一个Base类的子类Sub,在Sub中重写calculate()方法,将计算逻辑由乘法改为除法(X/Y)。注意,当分母为0时输出“Error”。注意:类中的属性必须私有,部分代码已给出,这次请交博客链接,不然打回重做!!!输入描述:两个整数输出描述:两个整数的积和商(int类型,不考虑小数情况)示例1输入:6 2输出:3 12示例2输入:1 0输出: Error 0**/
public class Base {private int x;private int y;public int getX() {return x;}public int getY() {return y;}public Base(int x, int y) {this.x = x;this.y = y;}public void calculate(){System.out.print(getX() * getY());}}
public class Sub extends Base{public Sub(int x, int y) {super(x, y);}@Overridepublic void calculate() {if (getY() == 0) {System.out.print("Error ");} else {System.out.print(getX() / getY()+" ");}}
}
import java.util.Scanner;public class Test {public static void main(String[] args) {Scanner scan = new Scanner(System.in);while (scan.hasNextInt()) {int x = scan.nextInt();int y = scan.nextInt();Base base = new Base(x, y);Sub sub = new Sub(x, y);sub.calculate();base.calculate();}}
}
运行结果如下