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?
public override string ToString(){} Implement the method so that it returns a string. The following example returns the name of the class in addition to the data specific to a particular instance of the class.
We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.
Overriding toString to be able to print out the object in a readable way when it is later read from the file.
toString() method of class Foo is not overridden, you will inherit the default . toString() from the Object class.
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.
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