Search code examples
javaobject-to-string

Why my overriding method of toString() has to be public?


I am new to Java and I am learning the basics. I was studying the toString method and how to override it in my own classes. I am just wondering why has toString to be public? is it because it is defined so in the Object class?


Solution

  • From official Oracle documentation:

    Modifiers

    The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.

    This because inheritance creates an IS-A relation between two classes, for which the Liskov substitution principle must be valid. Without having the previous constraint that would be impossible to enforce.