Search code examples
javainterfacepublicaccess-specifier

Why the overridden method should be public in this program?


import java.util.*;
interface AdvancedArithmetic{
  int divisor_sum(int n);
}
class MyCalculator implements AdvancedArithmetic
{
    int sum=0;
    int divisor_sum(int n)  //Why this method should be public?
    {
        for(int i=1;i<=n;i++)
        {
            if(n%i==0)
            sum=sum+i;
        }
        return sum;
    }
}

why the method inside class MyCalculator should be public? It shows an error like

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


Solution

  • int divisor_sum(int n) implements an interface method. Interface methods have public access (even if you don't specify it explicitly), so you cannot reduce the visibility of the method in the implementing class.

    Consider the following:

    MyCalculator mc = new MyCalculator();
    AdvancedArithmetic aa = mc;
    

    If you don't give divisor_sum() method in MyCalculator class a public access level, you won't be able to call it via the class reference (mc.divisor_sum(4)), but you would be able to call it via the interface reference (aa.divisor_sum(4)). This makes no sense, and therefore not allowed.