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.
This is because
Parent.a
andChild.a
are different things.Child#method()
@Override
sParent#method()
, as they are methods. Inheritance does not apply to fields.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 :
You can't. You are not reducing the visibility of
a
- you are creating a new, separate field which is also calleda
.