gokul ramalingam
gokul ramalingam

Reputation: 41

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

Upvotes: 1

Views: 601

Answers (2)

Stultuske
Stultuske

Reputation: 9427

Consider programming against interfaces. Your interface guarantees there is a method divisor_sum(int n) with public as (default) access modifier.

Now, imagine this:

public void doSomething(AdvancedArithmetic implementation) {
    int test = implementation.divisor_sum(5);
    // continue
}

If Java would allow a(ny) implementation of this interface to put it's access modifier of the method as more narrow than the one of the interface, this would lead to serious problems and breaking software, since the implementation is not following the contract of the interface.

Upvotes: 0

Eran
Eran

Reputation: 393801

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.

Upvotes: 4

Related Questions