Java - implements your own interface

Description

implements your own interface

Demo

// https://www.hackerrank.com/challenges/30-interfaces
// day 19: Interface

interface AdvancedArithmetic {
  int divisorSum(int n);
}
class Calculator implements AdvancedArithmetic {

  public int divisorSum(int n) {
    int sum = 1;/*from  w  ww . ja  v a2s . com*/

    for (int i = 2; i <= n; i++) {
      if (n % i == 0) {
        sum += i;
      }
    }
    return sum;
  }
}

public class Main {

  public static void main(String[] args) {
    int n = 10;

    AdvancedArithmetic myCalculator = new Calculator();
    int sum = myCalculator.divisorSum(n);
    System.out.println("I implemented: " + myCalculator.getClass().getInterfaces()[0].getName());
    System.out.println(sum);
  }
}

Related Topic