[HackerRank] JAVA Interface

OOSEDUS·2025년 3월 10일
0

해커랭크

목록 보기
1/13
post-thumbnail

문제

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


첫번째 시도 : Compile Error

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 접근 제한자를 추가해줘야한다.


두번째 시도 : Success

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;
    }
}

알아야하는 개념

  1. 클래스가 interface를 구현할때는 implements를 사용한다.
  2. 다른 클래스에서 구현한 함수를 자유롭게 사용하기 위해서는 public을 붙여줘야한다.
profile
성장 가능성 만땅 개발블로그

0개의 댓글