A Java interface can only contain method signatures and fields. The interface can be used to achieve polymorphism. In this problem, you will practice your knowledge on interfaces.
You are given an interface AdvancedArithmetic which contains a method signature int divisor_sum(int n). You need to write a class called MyCalculator which implements the interface.
divisorSum function just takes an integer as input and return the sum of all its divisors. For example divisors of 6 are 1, 2, 3 and 6, so divisor_sum should return 12. The value of n will be at most 1000.
Read the partially completed code in the editor and complete it. You just need to write the MyCalculator class only. Your class shouldn't be public.
Sample Input
6
Sample Output
I implemented: AdvancedArithmetic
12
class MyCalculator implements AdvancedArithmetic {
int divisor_sum(int n) {
int sum = 0;
for(int i = 1; i <= n/2; i++) {
if ((n%i)==0) {
sum += i;
}
}
return sum+n;
}
}
Compile time error
Solution.java:6: error: divisor_sum(int) in MyCalculator cannot implement divisor_sum(int) in AdvancedArithmetic
int divisor_sum(int n) {
^
attempting to assign weaker access privileges; was public
1 error
문제 원인 : MyCalculator의 divisor_sum 함수를 권한 접근이 되지 않아서 불러올 수 없던게 문제이다. 현재는 MyCalculator의 divisor_sum 함수가 default로 선언이 되어있어서 같은 클래스에서만 사용이 가능하다. 즉, 다른 클래스인 Solution 클래스에서는 접근이 막힌다.
해결 방법 : divisor_sum에 public 접근 제한자를 추가해줘야한다.
class MyCalculator implements AdvancedArithmetic {
public int divisor_sum(int n) {
int sum = 0;
for(int i = 1; i <= n/2; i++) {
if ((n%i)==0) {
sum += i;
}
}
return sum+n;
}
}