Thursday, 10 May 2018

Default method 'toString' overrides a member of 'java.lang.Object'

An interface "inherits" methods from the Object class. I wrote about this here1.

The quotes are appropriate, because Interfaces can only inherit from other Interfaces. An interface, when it does not have a super interface, declares all public non-final methods of the Object as members of the Interface (if not explicitly defined in the interface.

I recently attempted something like this TaxBracket2:

It doesn't work. In fact my IDE started complaining immediately with the following message.

Default method 'toString' overrides a member of 'java.lang.Object'

It is supposed to do that, so says the Java Language Spec3:

It is a compile-time error if a default method is override-equivalent with a non-private method of the class Object, because any class implementing the interface will inherit its own implementation of the method.

My colleague helpfully provided the alternative, which is to make an "elementString()" method in the Interface, which can be called in the toString() method of every Class that implements the Interface. (Further down in the JLS, this approach is almost word for word also given)

StackOverflow4 has a helpful link to the JDK mailinglist5 that explains it a lot more in depth.

One of the remarks that really struck a cord with me, is the fact that toString(), equals() and hashCode() are all basically related to the state of a Class, and do not belong in an Interface.

I have therefore decided to remove the offending default method.

References

[1] Do interfaces inherit from object class?
http://randomthoughtsonjavaprogramming.blogspot.nl/2017/07/do-interfaces-inherit-from-object-class.html
[2] Wikipedia - Tax bracket
https://en.wikipedia.org/wiki/Tax_bracket
[3] JLS 8 - 9.4.1.2. Requirements in Overriding
https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.4.3
[4] StackOverflow - Java8: Why is it forbidden to define a default method for a method from java.lang.Object?
https://stackoverflow.com/questions/24016962/java8-why-is-it-forbidden-to-define-a-default-method-for-a-method-from-java-lan
[5] Malinglist OpenJDK - Allow default methods to override Object's methods
http://mail.openjdk.java.net/pipermail/lambda-dev/2013-March/008435.html

No comments:

Post a Comment