分别实现与继承相关的、与抽象类相关的、与接口相关的匿名类的传参,实现: 九九乘法表 斐波那契数列前10项 1-100奇数的和
时间: 2024-11-22 10:39:47 浏览: 7
斐波那契数列与泰波那契数列的C++实现方法
首先,我们分别通过继承、抽象类和接口的匿名类来实现上述功能。
1. **继承与九九乘法表**:
```java
class MultiplicationTable {
public void printMultiplication(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.format("%d*%d=%d\t", i, j, i * j);
}
System.out.println();
}
}
}
// 匿名类实现
(new MultiplicationTable() {
public void printMultiplication(int n) {
this.printMultiplication(n);
}
}).printMultiplication(9); // 输出九九乘法表
```
2. **抽象类与斐波那契数列前10项**:
```java
abstract class Fibonacci {
abstract int next();
public static void main(String[] args) {
new Fibonacci() {
private int a = 0;
private int b = 1;
@Override
int next() {
return a + b;
}
public void printFibonacci(int count) {
for (int i = 0; i < count; i++) {
System.out.print(next() + " ");
if (i >= 9) break;
}
}
}.printFibonacci(10); // 输出斐波那契数列前10项
}
}
```
3. **接口与1-100奇数的和**:
```java
interface SumOfOddNumbers {
default int sum(int limit) {
int sum = 0;
for (int i = 1; i <= limit; i += 2) {
sum += i;
}
return sum;
}
}
public class Main {
public static void main(String[] args) {
SumOfOddNumbers oddSum = () -> {
return SumOfOddNumbers::sum;
};
System.out.println(oddSum.sum(100)); // 输出1到100奇数之和
}
}
```
阅读全文