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?

有帮助吗?

解决方案

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.

其他提示

Think about it: You subclass Gizmo with MyGizmo. This means that any place that a Gizmo can be used, you can use a MyGizmo in it's place. If some program does gizmoObject.toString() then that should work even if gizmoObject is not a Gizmo but a MyGizmo.

In particular, toString is used for printing & dumping objects and needs to be accessible on all objects.

When you override any method, the visibility of the override must be at least as visible as the base method.

When you override any method, the visibility of the override must be equal or more than the visibility of the base method

When overriding a method, you should declare the visibility of overridden method as the the one in the base class or wider.

Here is a note about the overriding rules I wrote it myself as a reference to me:

/* Access Modifiers */

1- Access modifier in child should be same or greater (the sequence: public - protected - default (package-private) - private). Access modifier in parent should not be private. If a child don't have access to the parent's method, then overriding the method without the @Override annotation will consider it as a new method.

/* Return Types */

2- Return type in child should be the same class or sub-class.

/* Exceptions */

3- If the parent's method throws checked exception, then the child's method can: a- throw the same exception or sub-class. b- not to throw any exceptions. c- throw runtime exceptions.

4- If the parent's method throws unchecked exception, then the child's method can: a- not to throw any exceptions. b- throw runtime exceptions.

5- If the parnet's method does not throw exception, then the child's method can: a- not to throw any exceptions. b- throw runtime exceptions.

Because you are overriding a method, you must define it as the prototype method or more than that.

when you override an sub class method visibility must be wider than parent class.

Wider to strict order:

public default protected private

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top