Skip to content
Snippets Groups Projects
Commit 42d5f754 authored by Goik Martin's avatar Goik Martin
Browse files

@Override example, equals(...) motivation

parent ce43f046
No related branches found
No related tags found
No related merge requests found
......@@ -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>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment