1.接⼝A有⼀个f(int a, int b)⽅法 2. B类实现接⼝A,重写f()⽅法,返回最⼤公约数; 3. C类实现接⼝A ,重写f()⽅法,返回最⼩公倍数;最⼩公倍数=(a*b)/最⼤公约数 4. D类提供show(A a)⽅法,以接⼝A的变量为参数,在⽅法内,打印出 a.f(4,6)⽅法的返回值; 5. 设计test类,包含main函数,⽤D类⽣成对象,对象调⽤show()⽅法分别以B类对象作为参数和以C类对象作为参数,求最⼤公约数和最⼩公倍数!
时间: 2024-02-27 12:56:21 浏览: 75
Java.docx static int foo(int a, byte b) { // ... }
下面是实现的代码:
```java
interface A {
int f(int a, int b);
}
class B implements A {
@Override
public int f(int a, int b) {
int max = Math.max(a, b);
int min = Math.min(a, b);
int remainder = max % min;
while (remainder != 0) {
max = min;
min = remainder;
remainder = max % min;
}
return min;
}
}
class C implements A {
@Override
public int f(int a, int b) {
int max = Math.max(a, b);
int min = Math.min(a, b);
int remainder = max % min;
while (remainder != 0) {
max = min;
min = remainder;
remainder = max % min;
}
return a * b / min;
}
}
class D {
public void show(A a) {
System.out.println(a.f(4, 6));
}
}
public class Test {
public static void main(String[] args) {
D d = new D();
B b = new B();
C c = new C();
System.out.print("最大公约数:");
d.show(b);
System.out.print("最小公倍数:");
d.show(c);
}
}
```
程序输出结果如下:
```
最大公约数:2
最小公倍数:12
```
阅读全文