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.
You cannot reduce the visibility of a inherited method. Here parent class has func() method which is public and overridden by the subclass TestClass which is private.
Asking for help, clarification, or responding to other answers. Making statements based on opinion; back them up with references or personal experience.
Java has four levels of visibility: public, protected, (default), private. The meaning of these is as follows: public - makes your methods accessible to any other class. protected - makes your methods accessible to any class in the same package OR any subclass of your class.
This is because Parent.a
and Child.a
are different things. Child#method()
@Override
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With