在Java中更改重写方法的访问修饰符? [英] Change the access modifier of an overridden method in Java?

查看:110
本文介绍了在Java中更改重写方法的访问修饰符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有理由可以更改被覆盖方法的访问修饰符?例如,

Is there a reason one can change the access modifier of an overridden method? For instance,

abstract class Foo{
    void start(){...}
}

然后将package-private访问修饰符更改为 public

And then change the package-private access modifier to public,

final class Bar extends Foo{
    @Override
    public void start(){...}
}

我只是出于好奇而问这个问题。

I'm just asking this question out of curiosity.

推荐答案

Java不允许您使访问修饰符更具限制性,因为这会违反规则子类实例应该可用于代替超类实例。但是当谈到使访问 less 限制性......好吧,也许超类是由不同的人编写的,并且他们没有预料到你想要使用他们的类的方式。

Java doesn't let you make the access modifier more restrictive, because that would violate the rule that a subclass instance should be useable in place of a superclass instance. But when it comes to making the access less restrictive... well, perhaps the superclass was written by a different person, and they didn't anticipate the way you want to use their class.

人们编写的程序和编程时出现的情况多种多样,语言设计者最好不要猜测程序员可能想要做什么他们的语言。如果没有充分的理由为什么程序员能够使访问说明符在子类中的限制性较小(例如),那么最好将该决定留给程序员。他们知道他们个人情况的具体情况,但语言设计师却不知道。所以我认为这是Java设计师的一个很好的调用。

The programs people write and the situations which arise when programming are so varied, that it's better for language designers not to "second-guess" what programmers might want to do with their language. If there is no good reason why a programmer should not be able to make access specifiers less restrictive in a subclass (for example), then it's better to leave that decision to the programmer. They know the specifics of their individual situation, but the language designer does not. So I think this was a good call by the designers of Java.

这篇关于在Java中更改重写方法的访问修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆