是否有理由可以更改覆盖方法的访问修饰符? 例如,
abstract class Foo{
void start(){...}
}
然后将程序包专用访问修饰符更改为public,
final class Bar extends Foo{
@Override
public void start(){...}
}
我只是出于好奇而问这个问题。
Java访问修饰符和覆盖方法的可能重复
Java不允许您对访问修饰符进行更严格的限制,因为这会违反以下规则:子类实例应该可以代替超类实例使用。但是,在减少访问限制方面……好吧,也许超类是由另一个人编写的,他们没有想到您要使用他们的类的方式。
人们编写的程序以及编程时所发生的情况千差万别,以使语言设计人员最好不要"猜测"一下程序员可能要用他们的语言做什么。如果没有充分的理由使程序员不能使访问说明符对子类的限制减少(例如),那么最好将决定权交给程序员。他们知道各自情况的细节,但语言设计者则不知道。因此,我认为这对Java的设计者来说是一个不错的选择。
扩展类意味着子类至少应提供与其他类相同的功能。
如果他扩大这一点,那不是问题。
扩展既可以是添加新方法,也可以是通过将现有方法提供给更多的类,例如将包访问方法公开。
只有一个,您可能希望覆盖在更多类中可见,因为默认没有修饰符,所以public会扩大它。
是的,那是我唯一能看到的好处。。。我不知道还有什么好处。
The explaination is this:-
It's a fundamental principle in OOP: the child class is a fully-fledged instance of the >parent class, and must therefore present at least the same interface as the parent class. >Making protected/public things less visible would violate this idea; you could make child >classes unusable as instances of the parent class.
class Person{
public void display(){
//some operation
}
}
class Employee extends Person{
private void display(){
//some operation
}
Person p=new Employee();
Here p is the object reference with type Person(super class),when we are calling >p.display() as the access modifier is more restrictive the object
reference p cannot access child object of type Employee
编辑:确定,我更改了答案以解决问题。
如果无法做到这一点,那么在某些情况下,一个类将无法实现Iterface并扩展一个类,因为它们具有使用不同访问修饰符的相同方法。
public Interface A {
public void method();
}
public abstract classs B {
protected void method();
}
public class AB extends B implements A {
/*
* This would't be possible if the access modifier coulnd't be changed
* to less restrictive
*/
public void method();
}
接口中定义的所有方法都是隐式公共的。
所有接口方法都必须是公共的。
您不能在公共或受保护的接口中使用非公共方法声明(上帝只知道受保护的接口的含义)。 java.sun.com/docs/books/jls/second_edition/html/参见9.1.4节
的确,在实现接口和扩展类时,它也是可能的。 病态编辑我的答案。