java小白 求助大佬
个 run 方法:
(2)编写个Dog类来实现Animal 接口并实
现ru 方法,rum 方法要计算1到n的和;
(3 )编写另个Bird 类来实现Animal 接
口并实现run 方法,run方法要计算n的阶
乘;
(4)编写测试类Test,在测试类Test 中分
别创建Dog类、Bird类的对象,用对象调用
run方法分别输出结果。 展开
interface Animal {
long run(long n);
}
class Dog implements Animal {
@Override
public long run(long n) {
int sum = 0;
for(int i = 0; i < n; i++) {
sum += i;
}
return sum;
}
}
class Bird implements Animal {
@Override
public long run(long n) {
if(n == 1) {
return 1;
}
return n * run(n - 1);
}
}
public class Test {
public static void main(String[] args) {
int n = 8;
Dog dog = new Dog();
System.out.println(dog.run(n));
Bird bird = new Bird();
System.out.println(bird.run(n));
}
}
2018-01-11 · 百度知道合伙人官方认证企业
接口(程序中的n根据需要自己定义):
public interface Animal {
public void run();
}
Dog类:
public class Dog implements Animal {
@Override
public void run() {
int count = 0;
for (int i = 1; i < 11; i++) {
count += i;
}
System.out.println("1到10的和是:" + count);
}
}
Bird 类:
public class Bird implements Animal {
@Override
public void run() {
int count = 1;
for (int i = 1; i < 6; i++) {
count *= i;
}
System.out.println("5的阶乘是:" + count);
}
}
试类Test:
public class Test {
public static void main(String[] args) {
Dog dog = new Dog();
dog.run();
Bird bird = new Bird();
bird.run();
}
}
运行结果: