From 42d5f7545ea6f644d761db207bec4185faadd864 Mon Sep 17 00:00:00 2001 From: Martin Goik <goik@hdm-stuttgart.de> Date: Mon, 11 Jun 2018 19:34:21 +0200 Subject: [PATCH] @Override example, equals(...) motivation --- Doc/Sd1/inheritance.xml | 52 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/Doc/Sd1/inheritance.xml b/Doc/Sd1/inheritance.xml index c63032531..caa241fd6 100644 --- a/Doc/Sd1/inheritance.xml +++ b/Doc/Sd1/inheritance.xml @@ -1273,6 +1273,24 @@ Type Rectangle</screen></td> </informaltable> </figure> + <figure xml:id="sd1_inherit_fig_shapeDefineEqualsExamples"> + <title>Defining <methodname>equals(...)</methodname>: + Expectations</title> + + <programlisting language="java">Rectangle r1 = new Rectangle(1, 2, 5, 4), + r2 = new Rectangle(1, 2, 1, 7), + r3 = new Rectangle(1, 2, 5, 4); + +Circle c = new Circle(-2, 3, 5); + +System.out.println(r1.equals("Hello")); // false: Differing classes Rectangle and String. +System.out.println(r1.equals(r2)); // false: Differing width and height. +System.out.println(r3.equals(r1)); // true: Two rectangles, + // identical (x|y), width and height. +System.out.println(r1.equals(c)); // false: Differing classes Rectangle and Circle. +System.out.println(c.equals(c)); // true: Object equal to itself.</programlisting> + </figure> + <figure xml:id="sd1_inherit_fig_shapeDefineEquals"> <title>Defining <methodname>equals(...)</methodname> of <classname>Shape</classname> instances</title> @@ -1402,4 +1420,38 @@ c.equals(r1): false</screen></td> </informaltable> </figure> </section> + + <section xml:id="sd1_inherit_sect_Override"> + <title>The <classname + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/lang/Override.html">@Override</classname> + annotation.</title> + + <figure xml:id="sd1_inherit_fig_overrideToString"> + <title>Overriding Object.toString()</title> + + <programlisting language="java">public class Shape { + + double x, y; + ... + @Override // Promise: Subsequent method overrides Object.toString(); + public String toString() { + return "(" + x + "|" + y + ")"; + } +}</programlisting> + </figure> + + <figure xml:id="sd1_inherit_fig_NotOverrideToString"> + <title>Failure: Not overriding Object.toString()</title> + + <programlisting language="java">public class Shape { + + double x, y; + ... + @Override <emphasis role="red">// Error: method does not override a method from a supertype</emphasis> + public String toString(int value) { + return "(" + x + "|" + y + ")"; + } +}</programlisting> + </figure> + </section> </chapter> -- GitLab