Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 516
mikey Avatar asked Mar 17 '13 23:03

mikey


People also ask

What is public override string toString?

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.

What happen if we override toString () method?

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.

Why is it needed to override toString () method in a DTO class?

Overriding toString to be able to print out the object in a readable way when it is later read from the file.

What happens if we don't override toString?

toString() method of class Foo is not overridden, you will inherit the default . toString() from the Object class.


1 Answers

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.

like image 163
Jack Avatar answered Sep 24 '22 23:09

Jack