【问题标题】:Why the overridden method should be public in this program?为什么重写的方法应该在这个程序中公开?
【发布时间】:2018-11-16 03:17:49
【问题描述】:
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;
    }
}

为什么类 MyCalculator 中的方法应该是公开的? 它显示一个错误,如

错误:MyCalculator 中的 divisor_sum(int) 无法在 AdvancedArithmetic 中实现 divisor_sum(int) int divisor_sum(int n) ^ 试图分配较弱的访问权限;是公开的 1 个错误

【问题讨论】:

  • 接口上的所有方法(Java 9 之前)都是公共的,无论您是否声明它们。

标签: java interface public access-specifier


【解决方案1】:

考虑针对接口进行编程。 您的界面保证有一个方法 divisor_sum(int n)public 作为(默认)访问修饰符。

现在,想象一下:

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

如果 Java 允许此 interface 的(纽约)实现将其 access modifier 的方法设置为比 interface 更窄,这将导致严重的问题和破坏软件,因为实施不遵循interface的合同。

【讨论】:

    【解决方案2】:

    int divisor_sum(int n) 实现了一个接口方法。接口方法具有public 访问权限(即使您没有显式指定它),因此您不能降低该方法在实现类中的可见性。

    考虑以下几点:

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

    如果你不给MyCalculator 类中的divisor_sum() 方法public 访问级别,你将无法通过类引用(mc.divisor_sum(4)) 调用它,但你可以通过接口引用 (aa.divisor_sum(4)) 调用它。这是没有意义的,因此是不允许的。

    【讨论】:

      猜你喜欢
      • 2016-07-17
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 2012-02-25
      • 2016-08-29
      相关资源
      最近更新 更多