编写一个类,该类有一个方法public int f(int a,int b),该方法返回a 和b 的最大公约数。然后再 编写一个该类的子类,要求子类重写方法f,而且重写的方法将返回a 和b 的最小公倍数。要求在重写 的方法的方法体中首先调用被隐藏的方法返回a 和b 的最大公约数m,然后将乘积(a*b)/ m 返回。要求 在应用程序的主类中分别使用父类和子类创建对象,并分别调用方法f 计算两个正整数的最大公约数 和最小公倍数。
时间: 2024-02-09 21:13:22 浏览: 18
好的,下面是代码实现:
```
public class MathUtil {
public int f(int a, int b) {
if (a == 0 || b == 0) {
return 0;
}
if (a < b) {
int temp = a;
a = b;
b = temp;
}
while (b != 0) {
int temp = a % b;
a = b;
b = temp;
}
return a;
}
}
public class MathUtilSub extends MathUtil {
@Override
public int f(int a, int b) {
int m = super.f(a, b);
return a * b / m;
}
}
public class Test {
public static void main(String[] args) {
MathUtil mathUtil = new MathUtil();
MathUtilSub mathUtilSub = new MathUtilSub();
int a = 12, b = 18;
System.out.println("a和b的最大公约数为:" + mathUtil.f(a, b));
System.out.println("a和b的最小公倍数为:" + mathUtilSub.f(a, b));
}
}
```
在父类MathUtil中,实现了求最大公约数的方法f,使用辗转相除法。
在子类MathUtilSub中,重写了方法f,先调用父类的f方法求出最大公约数m,然后再计算最小公倍数。
在主方法中,分别使用父类和子类创建对象,调用f方法计算最大公约数和最小公倍数。