为什么我们可以降低扩展类中属性的可见性? [英] Why can we reduce visibility of a property in extended class?

查看:120
本文介绍了为什么我们可以降低扩展类中属性的可见性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个班级,家长

public class Parent {
    public String a = "asd";

    public void method() {

    }
}

儿童

public class Child extends Parent{
    private String a = "12";

    private void method() {

    }
}

Child 中,我尝试覆盖父方法,这会产生编译时错误无法降低方法的可见性这很好。

In Child, I try to override the parent method which gives a compile time error of cannot reduce visibility of a method which is fine.

但是,为什么此错误不适用于属性 A ?我也降低了 a 的可见性,但它没有出错。

But, why is this error not applicable to property a? I am also reducing visibility of a, but it doesn't give an error.

推荐答案

这是因为 Parent.a Child.a 是不同的事情。 Child#method() @Override s Parent#method(),因为它们是方法。继承不适用于字段。

This is because Parent.a and Child.a are different things. Child#method() @Overrides Parent#method(), as they are methods. Inheritance does not apply to fields.


来自 Oracle JavaTM教程 - 继承,它被写成:


  • 继承的字段可以直接使用,就像任何其他字段一样。

  • 你可以在子类中声明一个与超类中的字段相同的字段,从而隐藏它(不推荐)。

  • 您可以在子类中声明不在超类中的新字段。

这篇关于为什么我们可以降低扩展类中属性的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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