Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can we reduce visibility of a property in extended class?

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.

like image 736
Bhuvan Avatar asked Jul 13 '14 05:07

Bhuvan


People also ask

How can you reduce the visibility of inheritance?

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.

Can we increase the visibility of the overridden method?

Asking for help, clarification, or responding to other answers. Making statements based on opinion; back them up with references or personal experience.

What is the visibility of public class?

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.


1 Answers

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.
like image 92
Unihedron Avatar answered Oct 01 '22 20:10

Unihedron