zoukankan      html  css  js  c++  java
  • 接口2

    按要求编写Java程序:

    (1)编写一个接口:InterfaceA,只含有一个方法int method(int n);

    (2)编写一个类:ClassA来实现接口InterfaceA,实现int method(int n)接口方法时,要求计算1到n的和;

    (3)编写另一个类:ClassB来实现接口InterfaceA,实现int method(int n)接口方法时,要求计算n的阶乘(n!);

    (4)编写测试类E,在测试类E的main方法中使用接口回调的形式来测试实现接口的类。

    1 public interface InterfaceA {
    2 
    3     int method(int n);
    4 }
     1 public class ClassA implements InterfaceA {
     2 
     3     @Override
     4     public int method(int n) {
     5         int sum = 0;
     6         for (int i = 1; i <= n; i++) {
     7             sum += i;
     8         }
     9         return sum;
    10     }
    11 
    12 }
     1 public class ClassB implements InterfaceA {
     2 
     3     @Override
     4     public int method(int n) {
     5         int jx = 1;
     6         for (int i = 1; i <= n; i++) {
     7             jx *= i;
     8         }
     9         return jx;
    10     }
    11 
    12 }
    1     public static void main(String[] args) {
    2 
    3         InterfaceA a = new ClassA();
    4         System.out.println("1到50的和=" + a.method(50));
    5         
    6         InterfaceA b = new ClassB();
    7         System.out.println("5! =" + b.method(5));
    8 
    9     }

    运行结果:

  • 相关阅读:
    移动端页面滚动性能调优
    外盘期货交易安全吗
    Vuetify的pagination功能踩坑
    oh-my-zsh自定义主题
    SSM整合
    Spring底层学习 1
    Node.js+Express day01
    JS+DOM conclusions
    tables+form+validation+Semantic HTML
    mybatis-利用association和collection实现一对一和一对多
  • 原文地址:https://www.cnblogs.com/ouyangtangfeng99/p/5523279.html
Copyright © 2011-2022 走看看