Why can we reduce visibility of a property in exte

2019-02-06 01:00发布

问题:

I have two classes, Parent:

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

    public void method() {

    }
}

And Child:

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

    private void method() {

    }
}

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.

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

回答1:

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.

From the Oracle JavaTM Tutorials - Inheritance, it was written that:

What You Can Do in a Subclass

  • The inherited fields can be used directly, just like any other fields.
  • You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
  • You can declare new fields in the subclass that are not in the superclass.


回答2:

You can't. You are not reducing the visibility of a - you are creating a new, separate field which is also called a.



回答3:

You are actually creating a private variable for Child. So, Child has two a's, one private and one public. Code below shows you how to access both. The methods are for the entire class (Parent) and its subclasses. Hence you get the error for the method.

Try this code to see the two a's :

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

    //private void method() {}

    public static void main(String[]args){
        Child c = new Child();
        Parent p = c;
        System.out.println(c.a + ", " + p.a);//12, asd

    }

}