为什么我们不能在方法覆盖时降低可见性(特别是 public 默认)

Why can't we reduce visibility while method overriding (specially public to default)


这是一个非常基本的概念,我们不能在覆盖时降低方法的可见性。但我想明白为什么?

class Parent{
  public void getData(){
   System.out.println("Parent GetData")
  }
}
class Child{
  void getData(){
   System.out.println("Parent GetData")
  }
}
public class OverridingDemo{
 public static void main(String[] args)
 {
  Parent p = new Child();
  p.getData(); // Error
 }
}

这里我们将 return 类型更改为默认类型,这允许访问相同的包。那为什么不能把return类型改为默认呢?
我确实明白,如果它是私有的或受保护的,那么在那种情况下就无法访问它,但为什么不默认呢?
是的,已经有很多线程可用,但我没能清楚地理解这个概念。
谢谢

这是关于 SOLID 规则之一的,Liskov substitution principle。这就是现代应用程序如何使用多态性和 OOP 范式。

从 运行 时间和编译时间开始,它是否是 package-private 访问修饰符。

这是不可能的,正是因为如果你有一个 class com.yadvendra.vehicles.Car 和 public 方法 int speed(),其他对象应该总是可以扩展它(添加新逻辑,如装饰器模式等)。想象一下,您要 return 您的 Car 对象指向其他包中的其他 class 对象,例如 com.yadvendra.view.CarView。此 class 想使用您的 public 方法 int speed(),但它不能,因为您将其可见性级别更改为 package-private。

I do understand that if it was private or protected then in that case it cant be accessed but why not for default?

默认访问没有什么不同。这是一个相对比较:不允许将范围缩小到 any 更严格的范围,因为它违反了超类的契约,如评论中所述。

旁注:您似乎明白 protecteddefault/package-private 范围更宽松。这不是真的。 protectedpackage-private 和更多。

API 的用户应该只认识父 class。您如何向他们解释他们现在不能使用某些方法,只是因为如果父 class 的实施降低了子 class 中的可见性?