From beb16cf634c83e6d66316df814b24461cda4bb8a Mon Sep 17 00:00:00 2001 From: Martin Goik <goik@hdm-stuttgart.de> Date: Tue, 30 Apr 2019 17:17:23 +0200 Subject: [PATCH] Slide cosmetics, new method def slide, exercise moved beyond constructor mention --- Doc/Sd1/objectsClasses.xml | 2881 ++++++++++++++++++------------------ 1 file changed, 1456 insertions(+), 1425 deletions(-) diff --git a/Doc/Sd1/objectsClasses.xml b/Doc/Sd1/objectsClasses.xml index 56b5c4831..1c9b00280 100644 --- a/Doc/Sd1/objectsClasses.xml +++ b/Doc/Sd1/objectsClasses.xml @@ -817,1827 +817,1858 @@ System.out.println("Perimeter=" + r.getPerimeter());</programlisting></td> </informaltable> </figure> - <qandaset defaultlabel="qanda" xml:id="sd1_qanda_geometry_Rectangle"> - <title>Modeling geometry objects: Rectangles</title> - - <qandaentry> - <question> - <para>We want to represent rectangles being defined by width and - height to allow for the subsequently demonstrated operations:</para> - - <programlisting language="java">final Rectangle r = new Rectangle(8, 5); <co - linkends="sw1CalloutRectangle-1" xml:id="constructor"/> - -System.out.println("Perimeter:" + r.getPerimeter()<co - linkends="sw1CalloutRectangle-2" xml:id="getPerimeter"/>); -System.out.println("Area:" + r.getArea()<co linkends="sw1CalloutRectangle-3" - xml:id="getArea"/>); - -r.setWidth(4); <co linkends="sw1CalloutRectangle-4" xml:id="setWidth"/> -r.setHeight(7); - -System.out.println("Perimeter:" + r.getPerimeter()); <co - linkends="sw1CalloutRectangle-5" - xml:id="sw1CalloutRectangle-5-co"/> -System.out.println("Area:" + r.getArea());</programlisting> - - <calloutlist> - <callout arearefs="constructor" xml:id="sw1CalloutRectangle-1"> - <para>Creating an instance of class - <classname>Rectangle</classname> by calling a non-default - constructor which allows for providing width (8) and height - (5).</para> - </callout> + <section xml:id="sd1_sect_accessControl"> + <title>Encapsulation and access control</title> - <callout arearefs="getPerimeter" xml:id="sw1CalloutRectangle-2"> - <para>Returning the rectangle's perimeter,</para> - </callout> + <figure xml:id="sd1_fig_accessObjectives"> + <title>Access control: Overall objectives</title> - <callout arearefs="getArea" xml:id="sw1CalloutRectangle-3"> - <para>Returning the rectangle's area.</para> - </callout> + <itemizedlist> + <listitem> + <para>Fine-grained control on attributes and methods.</para> + </listitem> - <callout arearefs="setWidth" xml:id="sw1CalloutRectangle-4"> - <para>Setting with and height to new values.</para> - </callout> + <listitem> + <para>Support <link + xlink:href="https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)">encapsulation</link> + / <link + xlink:href="https://en.wikipedia.org/wiki/Information_hiding">Information + hiding</link>.</para> - <callout arearefs="sw1CalloutRectangle-5-co" - xml:id="sw1CalloutRectangle-5"> - <para>Write (possibly) changed perimeter and area values.</para> - </callout> - </calloutlist> + <para>Purpose: Hide implementation details within class or + package</para> + </listitem> + </itemizedlist> + </figure> - <para>You may start from the following - <classname>Rectangle</classname> class dummy implementation:</para> + <figure xml:id="sd1_fig_timeImplementation"> + <title>Example: Implementing time and date</title> - <programlisting language="java">/** - * Representing rectangular shapes. - * - */ -public class Rectangle { + <informaltable border="0"> + <tr> + <td valign="top"><programlisting language="java">public class Time { + private long <co linkends="sd1_callout_publicPrivateInterface-1" + xml:id="sd1_callout_publicPrivateInterface-1-co"/> secondsSince_2000_01_01; - /** - * - * @param width The rectangle's width - * @param heigth The rectangle's height - */ - public Rectangle (double width, double heigth) { - //TODO + public int getSecond() { <co linkends="sd1_callout_publicPrivateInterface-2" + xml:id="sd1_callout_publicPrivateInterface-2-co"/> + return + (int) secondsSince_2000_01_01 % (60); } - /** - * @return The rectangle's area. - */ - public double getArea() { - return 0; // TODO + public int getMinute() {<coref + linkend="sd1_callout_publicPrivateInterface-2-co"/> + return (int) + (secondsSince_2000_01_01 / 60) % 60; } + // ... +}</programlisting></td> - /** - * @return The rectangle's perimeter. - */ - public double getPerimeter() { - return 0; // TODO - } + <td valign="top"><programlisting language="java">public class Time { + private int second, minute,<coref + linkend="sd1_callout_publicPrivateInterface-1-co"/> + hour,day, month, year; - /** - * @return The rectangle's width. - */ - public double getWidth() { - return 0; // TODO + public int getSecond() { <coref + linkend="sd1_callout_publicPrivateInterface-2-co"/> + return second; } - /** - * @param width The rectangle's new width - */ - public void setWidth(double width) { - // TODO + public int getMinute() { <coref + linkend="sd1_callout_publicPrivateInterface-2-co"/> + return minute; } + // ... +}</programlisting></td> + </tr> + </informaltable> - /** - * @return The rectangle's height. - */ - public double getHeight() { - return 0; // TODO - } + <calloutlist role="slideExclude"> + <callout arearefs="sd1_callout_publicPrivateInterface-1-co" + xml:id="sd1_callout_publicPrivateInterface-1"> + <para>Private attributes only accessible inside class.</para> + </callout> - /** - * @param height The rectangle's new height - */ - public void setHeight(double height) { - // TODO + <callout arearefs="sd1_callout_publicPrivateInterface-2-co" + xml:id="sd1_callout_publicPrivateInterface-2"> + <para>Public interface accessible by arbitrary classes.</para> + </callout> + </calloutlist> + </figure> + + <figure xml:id="sd1_fig_timeAccessViolation"> + <title>Access violation</title> + + <programlisting language="java">public class Q { + public static void main(String[] args) { + + Time t = new Time(); + + // Error: 'secondsSince_2000_01_01' has private access in 'Time' + t.secondsSince_2000_01_01 = 33445354L; } }</programlisting> - </question> + </figure> - <answer> - <para>First we define two instance variables <code - language="java">width</code> and <code language="java">height</code> - representing a <classname>Rectangle</classname>'s corresponding two - parameters <code language="java">width</code> and <code - language="java">height</code>:</para> + <figure xml:id="sd1_fig_AccessRules"> + <title>Access rules</title> - <programlisting language="java">public class Rectangle { + <informaltable border="1"> + <colgroup width="20%"/> - // Instance variables representing a rectangle's parameters - private double <emphasis role="bold">width</emphasis>, <emphasis role="bold">height</emphasis>; -... -}</programlisting> + <colgroup width="20%"/> - <para>Next we allow for changing these two parameters:</para> + <colgroup width="20%"/> - <programlisting language="java">public class Rectangle { + <colgroup width="20%"/> - // Instance variables representing a rectangle's parameters - private double width, height; + <colgroup width="20%"/> -... - /** - * @param width Changing the rectangle's width - */ - public void setWidth(double w) { - <emphasis role="bold">width = w;</emphasis> - } + <tr> + <td><link + xlink:href="https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html">Access + Level</link></td> - /** - * @param width Changing the rectangle's height - */ - public void setHeight(double height) { - <emphasis role="bold">this.height = height;</emphasis> - } -... -}</programlisting> + <td>Other package</td> - <para>Note the subtle implementation difference between - <methodname>setWidth(...)</methodname> and - <methodname>setHeight(...)</methodname>:</para> + <td>Child class</td> - <glosslist> - <glossentry xml:id="glossMethodDiff1"> - <glossterm><methodname>setWidth(double - w)</methodname></glossterm> + <td>Same package</td> - <glossdef> - <para>We use the formal parameter name <quote>w</quote>. Its - name does not conflict with the instance variable name - <quote>width</quote> being defined at class level. We can - simply assign this value to our corresponding instance - variable using <code language="java">width = w;</code>.</para> - </glossdef> - </glossentry> + <td>Same class</td> + </tr> - <glossentry xml:id="xmlMethodDiff2"> - <glossterm><methodname>setHeight(double - height)</methodname></glossterm> + <tr> + <td><code language="java">public</code></td> - <glossdef> - <para>The method's formal parameter <quote>height</quote> - shadows the instance variable's name being defined at class - level. We need the <quote>this</quote> keyword in <code - language="java">this.height = height</code> to resolve the - ambiguity.</para> - </glossdef> - </glossentry> - </glosslist> + <td>yes</td> - <para>Both ways are perfectly legal. The complete implementation - including all remaining methods reads:</para> + <td>yes</td> - <programlisting language="java">/** - * Representing rectangular shapes. - * - */ -public class Rectangle { + <td>yes</td> - // Instance variables representing a rectangle's parameters - private double width, height; + <td>yes</td> + </tr> - /** - * - * @param width The rectangle's width - * @param heigth The rectangle's height - */ - public Rectangle (double width, double height) { - setWidth(width); - setHeight(height); - } - /** - * @return The rectangle's area. - */ - public double getArea() { - return width * height; - } + <tr> + <td><code language="java">protected</code></td> - /** - * @return The rectangle's perimeter. - */ - public double getPerimeter() { - return 2 * (width + height); - } + <td><emphasis role="red">no</emphasis></td> - /** - * @return The rectangle's width. - */ - public double getWidth() { - return width; - } - /** - * @param width The rectangle's new width - */ - public void setWidth(double w) { - width = w; - } + <td>yes</td> - /** - * @return The rectangle's height. - */ - public double getHeight() { - return height; - } + <td>yes</td> - /** - * @param width The rectangle's new height - */ - public void setHeight(double height) { - this.height = height; - } -}</programlisting> - </answer> - </qandaentry> - </qandaset> + <td>yes</td> + </tr> - <qandaset defaultlabel="qanda" xml:id="qandasetGeometry"> - <title>Modeling circles</title> + <tr> + <td><emphasis role="bold">Default</emphasis></td> - <qandadiv> - <qandaentry> - <question> - <para>This exercise is very similar to <xref - linkend="sd1_qanda_geometry_Rectangle"/>. With respect to the - upcoming section on inheritance its presence will be justified - later by <xref linkend="sw1SectGeometryInherit"/>.</para> + <td><emphasis role="red">no</emphasis></td> - <para>We provide a corresponding class - <classname>Circle</classname> dummy implementation:</para> + <td><emphasis role="red">no</emphasis></td> - <programlisting language="java">package step1.dummy; + <td>yes</td> -/** - * A circle of given radius - * - */ -public class Circle { - - /** - * A new circle - * - * @param radius - * The desired radius. - */ - public Circle(double radius) { - // TODO - } + <td>yes</td> + </tr> - /** - * @return The circle's area. - */ - public double getArea() { - return 0; // TODO - } + <tr> + <td><code language="java">private</code></td> - /** - * @return The circle's perimeter. - */ - public double getPerimeter() { - return 0; // TODO - } + <td><emphasis role="red">no</emphasis></td> - /** - * @return The circle's radius. - */ - public double getRadius() { - return 0; // TODO - } + <td><emphasis role="red">no</emphasis></td> - /** - * @param radius - * Setting the circle's radius to a new value. - */ - public void setRadius(double radius) { - // TODO - } -}</programlisting> + <td><emphasis role="red">no</emphasis></td> - <para>Instances of this class shall be usable in the following - fashion:</para> + <td>yes</td> + </tr> + </informaltable> + </figure> - <programlisting language="java">public static void main(String[] args) { - final Circle c = new Circle(2.3); + <figure xml:id="sd1_fig_tipChoseAccessLevel"> + <title><quote + xlink:href="https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html#visibility">Tips + on Choosing an Access Level</quote></title> - System.out.println("Radius:" + c.getRadius()); - System.out.println("Perimeter:" + c.getPerimeter()); - System.out.println("Area:" + c.getArea()); + <itemizedlist> + <listitem> + <para>Use the most restrictive access level that makes sense for a + particular member.</para> + </listitem> - // Changing the circle's radius to a different value - c.setRadius(4.7); + <listitem> + <para>Use <code language="java">private</code> unless you have a + good reason not to.</para> + </listitem> - System.out.println("Radius:" + c.getRadius()); - System.out.println("Perimeter:" + c.getPerimeter()); - System.out.println("Area:" + c.getArea()); -}</programlisting> + <listitem> + <para>Avoid <code language="java">public</code> fields except for + constants. Public fields tend linking to a particular + implementation and limit your flexibility in changing your + code.</para> + </listitem> + </itemizedlist> + </figure> - <para>Hint: Obviously you'll have to define an instance variable - within Circle to keep track of its current radius value. All - methods mentioned above simply depend on this single value.</para> - </question> + <qandaset defaultlabel="qanda" xml:id="sd1_qanda_oracleAccessExample"> + <title>Understanding access control</title> - <answer> - <para>We define an instance variable <code - language="java">radius</code> inside our class - <classname>Circle</classname>:</para> + <qandadiv> + <qandaentry> + <question> + <para>Follow the example given in <quote + xlink:href="https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html#figure:classes-access.gif">Classes + and Packages of the Example Used to Illustrate Access + Levels</quote> and define two respective classes + <classname>Alpha</classname> and <classname>Beta</classname> in + different packages. Supply suitable dummy methods and fields + illustrating both legal and illegal access.</para> + </question> - <programlisting language="java">public class Circle { + <answer> + <informaltable border="1"> + <tr> + <th><classname>Alpha</classname></th> - double radius; -... -}</programlisting> + <th><classname>Beta</classname></th> - <para>Next we implement our method to change a circle's - radius:</para> + <th><classname>AlphaSub</classname></th> - <programlisting language="java">public void setRadius(double r) { - radius = r; -}</programlisting> + <th><classname>Gamma</classname></th> + </tr> - <para>Note that we have chosen a different value for the method's - formal radius parameter to be <quote>r</quote> rather than - <quote>radius</quote>. Many people prefer to use radius here - making it easier for a programmer to recognize the expected name - in the generated <xref linkend="glo_Javadoc"/>:</para> + <tr> + <td valign="top"><programlisting language="java">package package_one; - <programlisting language="java">public void setRadius(double radius) { -<emphasis role="red"> this.</emphasis>radius = radius; -}</programlisting> +public class Alpha { - <para>This requires the usage of the <code - language="java">this</code> keyword to distinguish the formal - parameter in <methodname>setRadius(double radius)</methodname> - from the instance variable previously being defined within our - class <classname>Circle</classname>. In other words: We have to - resolve a name shadowing conflict.</para> + public int attribPublic; + protected int attribProtected; +/*Default*/ int attribDefault; + private int attribPrivate; - <para>The rest of the implementation is (quite) straightforward. A - complete class reads:</para> + void dummy(/* same class */) { + int v; + v = attribPublic; + v = attribProtected; + v = attribDefault; + v = attribPrivate; + } +}</programlisting></td> - <programlisting language="java">package step1; + <td valign="top"><programlisting language="java">package package_one; -/** - * A circle of given radius - * - */ -public class Circle { +public class Beta { - double radius; - /** - * A new circle - * @param radius The desired radius. - */ - public Circle(double radius) { - setRadius(radius); - } - /** - * @return The circle's area. - */ - public double getArea() { - return radius * radius * Math.PI; - } - /** - * @return The circle's perimeter. - */ - public double getPerimeter() { - return 2 * Math.PI * radius; - } - /** - * @return The circle's radius. - */ - public double getRadius() { - return radius; - } - /** - * @param radius Setting the circle's radius to a new value. - */ - public void setRadius(double radius) { - this.radius = radius; + void dummy(Alpha a) { + int v; + v = a.attribPublic; + v = a.attribProtected; + v = a.attribDefault; + v = a.<emphasis role="red">attribPrivate</emphasis>; } -}</programlisting> - </answer> - </qandaentry> - </qandadiv> - </qandaset> - - <qandaset defaultlabel="qanda" xml:id="sdQandaSvgAndTranslation"> - <title>Adding translations and <xref linkend="glo_SVG"/> export.</title> +}</programlisting></td> - <qandadiv> - <qandaentry> - <question> - <para>We want to add more features to tour - <classname>Circle</classname> and <classname>Rectangle</classname> - classes:</para> + <td valign="top"><programlisting language="java">//different package +package package_two; - <glosslist> - <glossentry> - <glossterm>Translations</glossterm> +import package_one.Alpha; - <glossdef> - <para>Add two more instance variables x and y and - corresponding setter methods to account for a shape's - translation vector with respect to the origin (0,0). The - following hint may be helpful:</para> +public class AlphaSub + extends Alpha { - <programlisting language="java">/** - * @param x The circle's x center coordinate value - */ -public void setX(double x) { - // TODO -} -/** - * @param y The circle's y center coordinate value - */ -public void setY(double y) { - // TODO -}</programlisting> - <para>You may as well extend the constructors of - <classname>Rectangle</classname> and - <classname>Circle</classname> to accept center coordinates - as well:</para> + void dummy(/* Inherited */) { + int v; + v = attribPublic; + v = attribProtected; + v = <emphasis role="red">attribDefault</emphasis>; + v = <emphasis role="red">attribPrivate</emphasis>; + } +}</programlisting></td> - <programlisting language="java">public class Rectangle { + <td valign="top"><programlisting language="java">//different package +package package_two; +import package_one.Alpha; -... - /** - * Rectangle having center coordinates x, y, width and height. - * - * @param x The rectangle center's x-coordinate - * @param y The rectangle center's y-coordinate - * @param width The rectangle's width - * @param height The rectangle's height - */ - public Rectangle(double x, double y, double width, double height) { - ... - } - ... -}</programlisting> +public class Gamma { - <programlisting language="java">public class Circle { - ... - /** - * Circle having center coordinates x, y and radius r. - * - * @param x The circle center's x-coordinate - * @param y The circle center's y-coordinate - * @param radius The circle's radius - */ - public Circle(double x, double y, double radius) { - ... - } - ... -}</programlisting> - </glossdef> - </glossentry> - <glossentry> - <glossterm><xref linkend="glo_SVG"/> export</glossterm> - <glossdef> - <para>We would like Rectangle and Circle instances to be - visualized as <xref linkend="glo_SVG"/> graphics. <link - xlink:href="http://www.w3schools.com/graphics/svg_examples.asp">SVG - Examples</link> provides editor samples both for <link - xlink:href="http://www.w3schools.com/graphics/svg_circle.asp">circles</link> - and <link - xlink:href="http://www.w3schools.com/graphics/svg_rect.asp">rectangles</link>. - Add a method <methodname>void writeSvg()</methodname> to - both of your classes which allows for <xref - linkend="glo_SVG"/> code being written to standard output. - Use <methodname>System.out.println(...)</methodname> calls - to create the desired <xref linkend="glo_SVG"/> output. You - may need <code language="java">\"</code> to escape double - quotes as in the subsequent example or use single attribute - quotes instead:</para> - - <programlisting language="java">System.out.println("<rect width=\"20\"" ...</programlisting> - </glossdef> - </glossentry> - </glosslist> + void dummy(Alpha a) { + int v; + v = a.attribPublic; + v = a.<emphasis role="red">attribProtected</emphasis>; + v = a.<emphasis role="red">attribDefault</emphasis>; + v = a.<emphasis role="red">attribPrivate</emphasis>; + } +}</programlisting></td> + </tr> + </informaltable> - <para>The following code snippet may serve to illustrate the - intended use of <methodname>void writeSvg()</methodname>:</para> - - <programlisting language="java">public class Driver { - - public static void main(String[] args) { + <note> + <para>Notice the related follow up <link + linkend="sd1_qanda_protectedAccessProblem">inheritance + exercise</link>.</para> + </note> + </answer> + </qandaentry> + </qandadiv> + </qandaset> - System.out.println("<!DOCTYPE html><html><body>"); - System.out.println(" <svg width='300' height='200' >"); + <qandaset defaultlabel="qanda" xml:id="sd1_qanda_whyTimeMinuteCast"> + <title>Explaining times</title> - // Draw a rectangle as SVG - final Rectangle r = new Rectangle(5, 4); - r.setX(2); - r.setY(1); - r.writeSvg(); + <qandadiv> + <qandaentry> + <question> + <para>In <xref linkend="sd1_fig_timeImplementation"/> we + have:</para> - // Draw a circle as SVG - final Circle c = new Circle(3); - c.setX(3); - c.setY(1); - c.writeSvg(); - System.out.println(" </svg >"); - System.out.println("</body></html>"); - } -}</programlisting> + <programlisting language="java">public int getMinute() { + return + (int) (secondsSince_2000_01_01 / 60) % 60; + }</programlisting> - <para>Implement the method <methodname>void - writeSvg()</methodname> in both classes - <classname>Rectangle</classname> and - <classname>Circle</classname>. The following sample export is - intended for 300x200 pixel requiring to scale - <abbrev>e.g.</abbrev> the above circle's radius of three by a - factor of 20 resulting in an effective <tag - class="emptytag">circle r='60' ...</tag> value. This scaling is - being required for all parameters:</para> - - <programlisting language="java"><!DOCTYPE html> -<html> - <body> - <svg width='300' height='200' > - <emphasis role="bold"><rect width='100.0' height='80.0' x='40.0' y='20.0' - style='fill:rgb(0,255,0);stroke-width:3;stroke:rgb(0,0,0)'/></emphasis> - <emphasis role="bold"><circle r='60.0' cx='60.0' cy='20.0' - style='fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)'/></emphasis> - </svg > - </body> -</html></programlisting> + <orderedlist> + <listitem> + <para>Explain the underlying idea of the term <code + language="java">(secondsSince_2000_01_01 / 60) % + 60</code>.</para> + </listitem> - <para>You may copy this output into a file - <filename>svg.html</filename>. A web browser should visualize this - output as:</para> + <listitem> + <para>Explain the <code language="java">(int)</code> cast's + necessity. Why is there no overflow error about to + happen?</para> + </listitem> + </orderedlist> + </question> - <informalfigure> - <mediaobject> - <imageobject> - <imagedata fileref="Ref/Fig/svgGeometry.png"/> - </imageobject> - </mediaobject> - </informalfigure> - </question> + <answer> + <orderedlist> + <listitem> + <para>Every 60 seconds a new minute begins and seconds start + from zero again. Every 60 minutes a new our will start and + both seconds and minutes start from zero again.</para> - <answer> - <programlisting language="java">public class Rectangle { + <para>The term secondsSince_2000_01_01 / 60 amounts to the + number of minutes passed since 2000/01/01. Building the + remainder to 60 provides the current minute.</para> - private double x, y, width, height; - ... - /** - * @param x The rectangle's x center coordinate value - */ - public void setX(double x) { - this.x = x; - } - /** - * @param y The rectangle's y center coordinate value - */ - public void setY(double y) { - this.y = y; - } + <para>Example: If there are 4450 seconds elapsed this + amounts to 4450 / 3600 == 1 hour, (4450 / 60) % 60 == 14 + minutes and 4450 % 60 == 10 seconds.</para> + </listitem> -public void writeSvg() { - final int scale = 20; - System.out.println( - "<rect width='" + scale * width +"' height='" + scale * height + - "' x='" + scale * x + "'" + " y='" + scale * y + "'" + - "' style='fill:rgb(0,255,0);stroke-width:3;stroke:rgb(0,0,0)'/>"); - } -}</programlisting> + <listitem> + <para>The expression <code + language="java">(secondsSince_2000_01_01 / 60) % 60</code> + is of type long due to the presence of a <code + language="java">long</code> variable. However the + <quote>%</quote> operator guarantees the result to be in the + integer range 0 ... 59 which may thus be safely narrowed to + an <code language="java">int</code> value.</para> + </listitem> + </orderedlist> + </answer> + </qandaentry> + </qandadiv> + </qandaset> + </section> - <programlisting language="java">public class Circle { + <section xml:id="sd1_sect_getterSetter"> + <title>Getter and setter methods</title> - double x, y, radius; -... + <figure xml:id="sd1_fig_directVsSetterGetter"> + <title>Direct access <abbrev>vs.</abbrev> setter method</title> - /** - * @param x The circle's x center coordinate value - */ - public void setX(double x) { - this.x = x; - } - /** - * @param y The circle's y center coordinate value - */ - public void setY(double y) { - this.y = y; - } + <informaltable border="1"> + <tr> + <td valign="top"><programlisting language="java">package hour_second.direct; -public void writeSvg() { - final int scale = 20; +public class Time { + public int hour, minute; +}</programlisting><programlisting language="java">package hour_second; +import hour_second.direct.Time; - System.out.println( - "<circle r='" + scale * radius + - "' cx='" + scale * x + "'" + " cy='" + scale * y + - "' style='fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)'/>"); +public class DirectAccess { + Time time = new Time(); + void init() { + time.hour = 17; + time.minute = 45; + } +}</programlisting></td> - } -}</programlisting> - </answer> - </qandaentry> - </qandadiv> - </qandaset> + <td valign="top"><programlisting language="java">package hour_second.setter; - <section xml:id="sd1_sect_accessControl"> - <title>Encapsulation and access control</title> +public class Time { + private int hour, minute; + public void setTime(int h, int m) { + minute = m; + hour = h; + } +}</programlisting><programlisting language="java">package hour_second; +import hour_second.setter.Time; +public class SetterAccess { + Time time = new Time(); + void init() { time.setTime(17, 45);} +}</programlisting></td> + </tr> + </informaltable> + </figure> - <figure xml:id="sd1_fig_accessObjectives"> - <title>Access control: Overall objectives</title> + <figure xml:id="sd1_fig_whySetters"> + <title>Why adding setter methods?</title> <itemizedlist> <listitem> - <para>Fine-grained control on attributes and methods.</para> + <para>Allow for change of implementation.</para> </listitem> <listitem> - <para>Support <link - xlink:href="https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)">encapsulation</link> - / <link - xlink:href="https://en.wikipedia.org/wiki/Information_hiding">Information - hiding</link>.</para> + <para>Allow for non-business logic concerns. Examples:</para> - <para>Purpose: Hide implementation details within class or - package</para> + <itemizedlist> + <listitem> + <para>Logging</para> + </listitem> + + <listitem> + <para>Adding persistence</para> + </listitem> + </itemizedlist> </listitem> </itemizedlist> </figure> - <figure xml:id="sd1_fig_timeImplementation"> - <title>Example: Implementing time and date</title> + <figure xml:id="sd1_fig_implementJustSeconds"> + <title>Implementation by minutes only</title> - <informaltable border="0"> + <informaltable border="1"> <tr> - <td valign="top"><programlisting language="java">public class Time { - private long <co linkends="sd1_callout_publicPrivateInterface-1" - xml:id="sd1_callout_publicPrivateInterface-1-co"/> secondsSince_2000_01_01; - - public int getSecond() { <co linkends="sd1_callout_publicPrivateInterface-2" - xml:id="sd1_callout_publicPrivateInterface-2-co"/> - return - (int) secondsSince_2000_01_01 % (60); - } - public int getMinute() {<coref - linkend="sd1_callout_publicPrivateInterface-2-co"/> - return (int) - (secondsSince_2000_01_01 / 60) % 60; + <td valign="top"><programlisting language="java">package only_minute.direct; +public class Time { + // Minutes since 00:00 + public int minute; +}</programlisting><programlisting language="java">package only_minute; +import only_minute.direct.Time; +public class DirectAccess { + Time time = new Time(); + void init() { + <emphasis role="red">time.minute = 1065;</emphasis>// 17:45 } - // ... }</programlisting></td> - <td valign="top"><programlisting language="java">public class Time { - private int second, minute,<coref - linkend="sd1_callout_publicPrivateInterface-1-co"/> - hour,day, month, year; - - public int getSecond() { <coref - linkend="sd1_callout_publicPrivateInterface-2-co"/> - return second; - } - public int getMinute() { <coref - linkend="sd1_callout_publicPrivateInterface-2-co"/> - return minute; + <td valign="top"><programlisting language="java">package only_minute.setter; +public class Time { + private int minute; + public void setTime(int h, int m) { + minute = m + 60 * h; } - // ... +}</programlisting><programlisting language="java">package only_minute; +import only_minute.setter.Time; +public class SetterAccess { + Time time = new Time(); + void init() { <emphasis role="red">time.setTime(0, 0);</emphasis>} }</programlisting></td> </tr> </informaltable> + </figure> - <calloutlist role="slideExclude"> - <callout arearefs="sd1_callout_publicPrivateInterface-1-co" - xml:id="sd1_callout_publicPrivateInterface-1"> - <para>Private attributes only accessible inside class.</para> - </callout> + <qandaset defaultlabel="qanda" + xml:id="sd1QandaEmployeeFilesystemRepresentation"> + <title>File system representation</title> - <callout arearefs="sd1_callout_publicPrivateInterface-2-co" - xml:id="sd1_callout_publicPrivateInterface-2"> - <para>Public interface accessible by arbitrary classes.</para> - </callout> - </calloutlist> - </figure> + <qandadiv> + <qandaentry> + <question> + <para>In <xref linkend="sd1_qanda_refineAccessEmployee"/> you + moved the <classname>Employee</classname> class to a package + <package>model</package>.</para> - <figure xml:id="sd1_fig_timeAccessViolation"> - <title>Access violation</title> + <para>How are the corresponding <xref linkend="glo_Java"/> files + <filename>Employee.java</filename> and + <filename>Driver.java</filename> being represented? What about + the generated byte code files + <filename>Employee.</filename>class and + <filename>Driver.</filename>class?</para> - <programlisting language="java">public class Q { - public static void main(String[] args) { + <tip> + <para>Use your OS's file system explorer.</para> + </tip> + </question> - Time t = new Time(); + <answer> + <para>Depending on your type of project (Java, Maven,...) both + your <filename>.java</filename> source files and generated + <filename>.class</filename> files will be organized below their + respective entry level directories. The following typical layout + depends on your Java development environment / <xref + linkend="glo_IDE"/>:</para> - // Error: 'secondsSince_2000_01_01' has private access in 'Time' - t.secondsSince_2000_01_01 = 33445354L; - } -}</programlisting> - </figure> + <glosslist> + <glossentry> + <glossterm><filename>.java</filename> source + files</glossterm> - <figure xml:id="sd1_fig_AccessRules"> - <title>Access rules</title> + <glossdef> + <para>Below folder <filename>src</filename>.</para> + </glossdef> + </glossentry> - <informaltable border="1"> - <colgroup width="20%"/> + <glossentry> + <glossterm><filename>.class</filename> byte code + files</glossterm> - <colgroup width="20%"/> + <glossdef> + <para>Below folder <filename>bin</filename>.</para> + </glossdef> + </glossentry> + </glosslist> - <colgroup width="20%"/> + <para>Packages give rise to further sub directories both for + source code and their generated byte code + <quote>partners</quote>. The following example is a minor + variation of our employee example. The package + <package>model</package> has been transformed into + <package>company.model</package>:</para> - <colgroup width="20%"/> + <figure xml:id="sd1FigPackageHierarchy"> + <title>Package hierarchy of the employee example</title> - <colgroup width="20%"/> + <screenshot> + <info> + <title>On filesystem level the package + <package>company.model</package> becomes a subdirectory + <filename>model</filename> of sub directory + <filename>company</filename> for both our source + (<filename>src</filename>) and bytecode + (<filename>bin</filename>) file hierarchy.</title> + </info> - <tr> - <td><link - xlink:href="https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html">Access - Level</link></td> + <mediaobject> + <imageobject> + <imagedata fileref="Ref/Fig/packageHierarchy.png"/> + </imageobject> + </mediaobject> + </screenshot> + </figure> + </answer> + </qandaentry> + </qandadiv> + </qandaset> + </section> - <td>Other package</td> + <section xml:id="sd1_sect_methodSignature"> + <title>Signatures</title> - <td>Child class</td> + <figure xml:id="sd1_fig_typeSignatureDef"> + <title>Defining type signatures</title> - <td>Same package</td> + <programlisting language="java">boolean <co + linkends="sd1_fig_typeSignatureDef-1" + xml:id="sd1_fig_typeSignatureDef-1-co"/> <link + xlink:href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#startsWith(java.lang.String,int)">startsWith</link>(String prefix, int toffset) <co + linkends="sd1_fig_typeSignatureDef-2" + xml:id="sd1_fig_typeSignatureDef-2-co"/> </programlisting> + + <calloutlist> + <callout arearefs="sd1_fig_typeSignatureDef-1-co" + xml:id="sd1_fig_typeSignatureDef-1"> + <para>Return type boolean</para> + </callout> - <td>Same class</td> - </tr> + <callout arearefs="sd1_fig_typeSignatureDef-2-co" + xml:id="sd1_fig_typeSignatureDef-2"> + <para>Number of arguments among with their respective types and + order:</para> - <tr> - <td><code language="java">public</code></td> + <para>Two argument types: String followed by <code + language="java">int</code>. Consider:</para> - <td>yes</td> + <programlisting language="java">boolean startsWith(int toffset, String prefix) </programlisting> + </callout> + </calloutlist> + </figure> - <td>yes</td> + <figure xml:id="sd1_fig_typeSignature"> + <title>Type signature examples</title> - <td>yes</td> + <informaltable border="1"> + <colgroup width="81%"/> - <td>yes</td> - </tr> + <colgroup width="11%"/> + + <colgroup width="8%"/> <tr> - <td><code language="java">protected</code></td> + <th valign="top">Method</th> - <td><emphasis role="red">no</emphasis></td> + <th valign="top">Return type</th> - <td>yes</td> + <th valign="top">Argument type list</th> + </tr> - <td>yes</td> + <tr> + <td><methodname>void print()</methodname></td> - <td>yes</td> + <td>void</td> + + <td>(void)</td> </tr> <tr> - <td><emphasis role="bold">Default</emphasis></td> + <td><methodname>int add (int a, int b) </methodname></td> - <td><emphasis role="red">no</emphasis></td> + <td>int</td> - <td><emphasis role="red">no</emphasis></td> + <td>(int, int)</td> + </tr> - <td>yes</td> + <tr> + <td><methodname>int maximum (int a, int b)</methodname></td> - <td>yes</td> + <td>int</td> + + <td>(int, int)</td> </tr> <tr> - <td><code language="java">private</code></td> + <td><methodname>void print (int a, float b)</methodname></td> - <td><emphasis role="red">no</emphasis></td> + <td>void</td> - <td><emphasis role="red">no</emphasis></td> + <td>(int, float)</td> + </tr> - <td><emphasis role="red">no</emphasis></td> + <tr> + <td><methodname>void display (float a, int b)</methodname></td> - <td>yes</td> + <td>void</td> + + <td>(float, int)</td> </tr> </informaltable> </figure> - <figure xml:id="sd1_fig_tipChoseAccessLevel"> - <title><quote - xlink:href="https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html#visibility">Tips - on Choosing an Access Level</quote></title> - - <itemizedlist> - <listitem> - <para>Use the most restrictive access level that makes sense for a - particular member.</para> - </listitem> - - <listitem> - <para>Use <code language="java">private</code> unless you have a - good reason not to.</para> - </listitem> + <figure xml:id="sd1_fig_typeSignatureDetail"> + <title>Defining method signatures</title> + + <programlisting language="java">boolean <link + xlink:href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#startsWith(java.lang.String,int)">startsWith</link><co + linkends="sd1_fig_typeSignatureDef-1.2" + xml:id="sd1_fig_typeSignatureDef-1.2-co"/>(String prefix, int toffset) <co + linkends="sd1_fig_typeSignatureDef-2.2" + xml:id="sd1_fig_typeSignatureDef-2.2-co"/> </programlisting> + + <calloutlist> + <callout arearefs="sd1_fig_typeSignatureDef-1.2-co" + xml:id="sd1_fig_typeSignatureDef-1.2"> + <para>Method name <code language="java">startsWith</code>.</para> + </callout> - <listitem> - <para>Avoid <code language="java">public</code> fields except for - constants. Public fields tend linking to a particular - implementation and limit your flexibility in changing your - code.</para> - </listitem> - </itemizedlist> + <callout arearefs="sd1_fig_typeSignatureDef-2.2-co" + xml:id="sd1_fig_typeSignatureDef-2.2"> + <para>Number of arguments among with their respective types and + order.</para> + </callout> + </calloutlist> </figure> - <qandaset defaultlabel="qanda" xml:id="sd1_qanda_oracleAccessExample"> - <title>Understanding access control</title> + <figure xml:id="sd1_fig_methodSignature"> + <title>Method signature examples</title> - <qandadiv> - <qandaentry> - <question> - <para>Follow the example given in <quote - xlink:href="https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html#figure:classes-access.gif">Classes - and Packages of the Example Used to Illustrate Access - Levels</quote> and define two respective classes - <classname>Alpha</classname> and <classname>Beta</classname> in - different packages. Supply suitable dummy methods and fields - illustrating both legal and illegal access.</para> - </question> + <informaltable border="1"> + <colgroup width="81%"/> - <answer> - <informaltable border="1"> - <tr> - <th><classname>Alpha</classname></th> + <colgroup width="11%"/> - <th><classname>Beta</classname></th> + <colgroup width="8%"/> - <th><classname>AlphaSub</classname></th> + <tr> + <th valign="top">Method</th> - <th><classname>Gamma</classname></th> - </tr> + <th valign="top">Method name</th> - <tr> - <td valign="top"><programlisting language="java">package package_one; + <th colspan="1" valign="top">Method signature</th> + </tr> -public class Alpha { + <tr> + <td><methodname>void print() </methodname></td> - public int attribPublic; - protected int attribProtected; -/*Default*/ int attribDefault; - private int attribPrivate; + <td>print</td> - void dummy(/* same class */) { - int v; - v = attribPublic; - v = attribProtected; - v = attribDefault; - v = attribPrivate; - } -}</programlisting></td> + <td>(void)</td> + </tr> - <td valign="top"><programlisting language="java">package package_one; + <tr> + <td><methodname>int add (int a, int b)</methodname></td> -public class Beta { + <td>add</td> + <td>(int, int)</td> + </tr> + <tr> + <td><methodname>int maximum (int a, int b)</methodname></td> + <td>maximum</td> + <td>(int, int)</td> + </tr> + <tr> + <td><methodname>void print (int a, float b)</methodname></td> - void dummy(Alpha a) { - int v; - v = a.attribPublic; - v = a.attribProtected; - v = a.attribDefault; - v = a.<emphasis role="red">attribPrivate</emphasis>; - } -}</programlisting></td> + <td>print</td> - <td valign="top"><programlisting language="java">//different package -package package_two; + <td>(int, float)</td> + </tr> -import package_one.Alpha; + <tr> + <td><methodname>void display (float a, int b)</methodname></td> -public class AlphaSub - extends Alpha { + <td>display</td> + <td>(float, int)</td> + </tr> + </informaltable> + </figure> + </section> - void dummy(/* Inherited */) { - int v; - v = attribPublic; - v = attribProtected; - v = <emphasis role="red">attribDefault</emphasis>; - v = <emphasis role="red">attribPrivate</emphasis>; - } -}</programlisting></td> + <section xml:id="sd1_sect_methodOverloading"> + <title>Method overloading</title> - <td valign="top"><programlisting language="java">//different package -package package_two; -import package_one.Alpha; + <figure xml:id="sd1_fig_overloadingPrinciple"> + <title>Method overloading: Same name, different signature</title> -public class Gamma { + <informaltable border="0"> + <tr> + <td rowspan="2" valign="top"><programlisting language="java">public class Print { + public void print() { // (void) + System.out.println("No argument"); + } + public void print(int i) { // (int) + System.out.println("int value " + i); + } + public void print(double d) { // (double) + System.out.println("double value " + d); + } + public void print(int i, int j) { // (int, int) + System.out.println("Two int values "+ + i + " and " + j); + } +}</programlisting></td> + <td valign="top"><programlisting language="java">Print p = new Print(); +p.print(); +p.print(33); +p.print(4.333); +p.print(-1, 7);</programlisting></td> + </tr> + <tr> + <td valign="top"><screen>No argument +int value 33 +double value 4.333 +Two int values -1 and 7</screen></td> + </tr> + </informaltable> + </figure> + <figure xml:id="sd1_fig_overloadingAlternateNames"> + <title>Overloading, alternate names</title> - void dummy(Alpha a) { - int v; - v = a.attribPublic; - v = a.<emphasis role="red">attribProtected</emphasis>; - v = a.<emphasis role="red">attribDefault</emphasis>; - v = a.<emphasis role="red">attribPrivate</emphasis>; - } -}</programlisting></td> - </tr> - </informaltable> + <itemizedlist> + <listitem> + <para>Static polymorphism.</para> + </listitem> - <note> - <para>Notice the related follow up <link - linkend="sd1_qanda_protectedAccessProblem">inheritance - exercise</link>.</para> - </note> - </answer> - </qandaentry> - </qandadiv> - </qandaset> + <listitem> + <para>Compile time binding.</para> + </listitem> - <qandaset defaultlabel="qanda" xml:id="sd1_qanda_whyTimeMinuteCast"> - <title>Explaining times</title> + <listitem> + <para>Early binding.</para> + </listitem> + </itemizedlist> + </figure> - <qandadiv> - <qandaentry> - <question> - <para>In <xref linkend="sd1_fig_timeImplementation"/> we - have:</para> + <figure xml:id="sd1_fig_noOverloadingInC"> + <title>No such concept in C</title> - <programlisting language="java">public int getMinute() { - return - (int) (secondsSince_2000_01_01 / 60) % 60; - }</programlisting> + <programlisting language="c">void print() { + printf("No argument\n"); +} - <orderedlist> - <listitem> - <para>Explain the underlying idea of the term <code - language="java">(secondsSince_2000_01_01 / 60) % - 60</code>.</para> - </listitem> +void print(int i) { <emphasis role="bold"> /* Error: redefinition of ‘print’ */</emphasis> + printf("int value %d\n", i); +} - <listitem> - <para>Explain the <code language="java">(int)</code> cast's - necessity. Why is there no overflow error about to - happen?</para> - </listitem> - </orderedlist> - </question> +void main(void) { + print(); + print(33); +}</programlisting> + </figure> - <answer> - <orderedlist> - <listitem> - <para>Every 60 seconds a new minute begins and seconds start - from zero again. Every 60 minutes a new our will start and - both seconds and minutes start from zero again.</para> + <figure xml:id="sd1_fig_distinctReturnType"> + <title>What about return type?</title> - <para>The term secondsSince_2000_01_01 / 60 amounts to the - number of minutes passed since 2000/01/01. Building the - remainder to 60 provides the current minute.</para> + <programlisting language="java">public class Person { + String getDetails() { return "dummy";} + int getDetails() { return 1;} // Error: 'getDetails()' is already + // defined in 'Person' +}</programlisting> - <para>Example: If there are 4450 seconds elapsed this - amounts to 4450 / 3600 == 1 hour, (4450 / 60) % 60 == 14 - minutes and 4450 % 60 == 10 seconds.</para> - </listitem> + <informaltable border="1"> + <tr> + <th rowspan="2" valign="top">Return type</th> - <listitem> - <para>The expression <code - language="java">(secondsSince_2000_01_01 / 60) % 60</code> - is of type long due to the presence of a <code - language="java">long</code> variable. However the - <quote>%</quote> operator guarantees the result to be in the - integer range 0 ... 59 which may thus be safely narrowed to - an <code language="java">int</code> value.</para> - </listitem> - </orderedlist> - </answer> - </qandaentry> - </qandadiv> - </qandaset> - </section> + <th colspan="2">Method signature</th> + </tr> - <section xml:id="sd1_sect_getterSetter"> - <title>Getter and setter methods</title> + <tr> + <th>Method name</th> - <figure xml:id="sd1_fig_directVsSetterGetter"> - <title>Direct access <abbrev>vs.</abbrev> setter method</title> + <th>Argument type list</th> + </tr> - <informaltable border="1"> <tr> - <td valign="top"><programlisting language="java">package hour_second.direct; + <td>String</td> -public class Time { - public int hour, minute; -}</programlisting><programlisting language="java">package hour_second; -import hour_second.direct.Time; + <td>getDetails</td> -public class DirectAccess { - Time time = new Time(); - void init() { - time.hour = 17; - time.minute = 45; - } -}</programlisting></td> + <td>(void)</td> + </tr> - <td valign="top"><programlisting language="java">package hour_second.setter; + <tr> + <td>int</td> -public class Time { - private int hour, minute; - public void setTime(int h, int m) { - minute = m; - hour = h; - } -}</programlisting><programlisting language="java">package hour_second; -import hour_second.setter.Time; -public class SetterAccess { - Time time = new Time(); - void init() { time.setTime(17, 45);} -}</programlisting></td> + <td>getDetails</td> + + <td>(void)</td> </tr> </informaltable> + + <para>Return type irrelevant, only method signature support in <xref + linkend="glo_Java"/>.</para> </figure> - <figure xml:id="sd1_fig_whySetters"> - <title>Why adding setter methods?</title> + <figure xml:id="sd1_fig_methodSignatureRatio"> + <title>Method signatures rationale</title> - <itemizedlist> - <listitem> - <para>Allow for change of implementation.</para> - </listitem> + <para>In <xref linkend="glo_Java"/> method signatures allow for + uniquely addressing a method within a given class e.g.:</para> - <listitem> - <para>Allow for non-business logic concerns. Examples:</para> + <para>The method named <code language="java">print</code> having an + int argument followed by a double:</para> - <itemizedlist> - <listitem> - <para>Logging</para> - </listitem> + <programlisting language="java">print(int, double)</programlisting> + </figure> - <listitem> - <para>Adding persistence</para> - </listitem> - </itemizedlist> - </listitem> - </itemizedlist> + <figure xml:id="sd1_fig_chooseByMethodSignature"> + <title>Method signatures rationale</title> + + <mediaobject> + <imageobject> + <imagedata fileref="Ref/ObjectsAndClasses/chooseOverloaded.svg"/> + </imageobject> + </mediaobject> </figure> - <figure xml:id="sd1_fig_implementJustSeconds"> - <title>Implementation by minutes only</title> + <figure xml:id="sd1_fig_sysoutPrintlnOverload"> + <title>Example: System.out.print(...)</title> - <informaltable border="1"> + <informaltable border="0"> <tr> - <td valign="top"><programlisting language="java">package only_minute.direct; -public class Time { - // Minutes since 00:00 - public int minute; -}</programlisting><programlisting language="java">package only_minute; -import only_minute.direct.Time; -public class DirectAccess { - Time time = new Time(); - void init() { - <emphasis role="red">time.minute = 1065;</emphasis>// 17:45 - } -}</programlisting></td> + <td><methodname + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-boolean-">print(boolean + b)</methodname></td> - <td valign="top"><programlisting language="java">package only_minute.setter; -public class Time { - private int minute; - public void setTime(int h, int m) { - minute = m + 60 * h; - } -}</programlisting><programlisting language="java">package only_minute; -import only_minute.setter.Time; -public class SetterAccess { - Time time = new Time(); - void init() { <emphasis role="red">time.setTime(0, 0);</emphasis>} -}</programlisting></td> + <td><methodname + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-char-">print(char + c)</methodname></td> </tr> - </informaltable> - </figure> - - <qandaset defaultlabel="qanda" - xml:id="sd1QandaEmployeeFilesystemRepresentation"> - <title>File system representation</title> - <qandadiv> - <qandaentry> - <question> - <para>In <xref linkend="sd1_qanda_refineAccessEmployee"/> you - moved the <classname>Employee</classname> class to a package - <package>model</package>.</para> - - <para>How are the corresponding <xref linkend="glo_Java"/> files - <filename>Employee.java</filename> and - <filename>Driver.java</filename> being represented? What about - the generated byte code files - <filename>Employee.</filename>class and - <filename>Driver.</filename>class?</para> - - <tip> - <para>Use your OS's file system explorer.</para> - </tip> - </question> - - <answer> - <para>Depending on your type of project (Java, Maven,...) both - your <filename>.java</filename> source files and generated - <filename>.class</filename> files will be organized below their - respective entry level directories. The following typical layout - depends on your Java development environment / <xref - linkend="glo_IDE"/>:</para> - - <glosslist> - <glossentry> - <glossterm><filename>.java</filename> source - files</glossterm> + <tr> + <td><methodname + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-char:A-">print(char[] + s)</methodname></td> - <glossdef> - <para>Below folder <filename>src</filename>.</para> - </glossdef> - </glossentry> + <td><methodname + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-double-">print(double + d)</methodname></td> + </tr> - <glossentry> - <glossterm><filename>.class</filename> byte code - files</glossterm> + <tr> + <td><methodname + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-float-">print(float + f)</methodname></td> - <glossdef> - <para>Below folder <filename>bin</filename>.</para> - </glossdef> - </glossentry> - </glosslist> + <td><methodname + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-int-">print(int + i)</methodname></td> + </tr> - <para>Packages give rise to further sub directories both for - source code and their generated byte code - <quote>partners</quote>. The following example is a minor - variation of our employee example. The package - <package>model</package> has been transformed into - <package>company.model</package>:</para> + <tr> + <td><methodname + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-long-">print(long + l)</methodname></td> - <figure xml:id="sd1FigPackageHierarchy"> - <title>Package hierarchy of the employee example</title> + <td><methodname + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-java.lang.Object-">print(Object + obj)</methodname></td> + </tr> - <screenshot> - <info> - <title>On filesystem level the package - <package>company.model</package> becomes a subdirectory - <filename>model</filename> of sub directory - <filename>company</filename> for both our source - (<filename>src</filename>) and bytecode - (<filename>bin</filename>) file hierarchy.</title> - </info> + <tr> + <td><methodname + xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-java.lang.String-">print(String + s)</methodname></td> - <mediaobject> - <imageobject> - <imagedata fileref="Ref/Fig/packageHierarchy.png"/> - </imageobject> - </mediaobject> - </screenshot> - </figure> - </answer> - </qandaentry> - </qandadiv> - </qandaset> + <td/> + </tr> + </informaltable> + </figure> </section> - <section xml:id="sd1_sect_methodSignature"> - <title>Signatures</title> - - <figure xml:id="sd1_fig_typeSignature"> - <title>Type signatures</title> + <section xml:id="sd1_sect_constructors"> + <title>Constructors</title> - <para>A method's return and arguments type list. Examples:</para> + <figure xml:id="sd1_fig_createRectangleConstructor"> + <title>Creating and initializing rectangles</title> <informaltable border="1"> - <colgroup width="75%"/> - - <colgroup width="12%"/> + <colgroup width="30%"/> - <colgroup width="13%"/> + <colgroup width="70%"/> <tr> - <th rowspan="2" valign="top">Method</th> + <td valign="top"><programlisting language="java">int a; +a = 33;</programlisting></td> - <th colspan="2">Type signature</th> + <td valign="top"><programlisting language="java">Rectangle r = new Rectangle(); + +r.width = 28; +r.height = 10; +r.hasSolidBorder = false;</programlisting></td> </tr> <tr> - <th>Return type</th> - - <th>Argument type list</th> + <th colspan="2"><para>Combining statements desired:</para></th> </tr> <tr> - <td><methodname>void print() {...}</methodname></td> - - <td>void</td> + <td valign="top"><programlisting language="java">int a = 33; // works!</programlisting></td> - <td>(void)</td> + <td valign="top"><programlisting language="java">Rectangle r = new Rectangle(28, 10, false); // <emphasis + role="red">how ???</emphasis></programlisting></td> </tr> + </informaltable> - <tr> - <td><methodname>int add (int a, int b) {...}</methodname></td> + <para>How to get this work?</para> + </figure> - <td>int</td> + <figure xml:id="sd1_fig_createRectangleDefineConstruct"> + <title>Defining a constructor</title> - <td>(int, int)</td> - </tr> + <programlisting language="java">public class Rectangle { + int width, height; + boolean hasSolidBorder; + ... + public <co linkends="sd1_callout_defineConstructor-1" + xml:id="sd1_callout_defineConstructor-1-co"/> Rectangle <co + linkends="sd1_callout_defineConstructor-2" + xml:id="sd1_callout_defineConstructor-2-co"/> (int width, int height, boolean hasSolidBorder){ + this.width = width; + this.height = height; + this.hasSolidBorder = hasSolidBorder; + } +}</programlisting> + </figure> - <tr> - <td><methodname>int maximum (int a, int b){...}</methodname></td> + <para>Similar to <xref linkend="fig_methodSyntax"/> but:</para> - <td>int</td> + <calloutlist> + <callout arearefs="sd1_callout_defineConstructor-1-co" + xml:id="sd1_callout_defineConstructor-1"> + <para>No return type declaration.</para> + </callout> - <td>(int, int)</td> - </tr> + <callout arearefs="sd1_callout_defineConstructor-2-co" + xml:id="sd1_callout_defineConstructor-2"> + <para>Constructor's name equals class name.</para> + </callout> + </calloutlist> - <tr> - <td><methodname>void print (int a, float b){...}</methodname></td> + <figure xml:id="sd1_fig_constructorSyntax"> + <title>Constructor syntax</title> - <td>void</td> + <programlisting language="java">constructorName (listOfArguments) { + [constructor body] +}</programlisting> - <td>(int, float)</td> - </tr> + <glosslist> + <glossentry> + <glossterm>Empty argument list</glossterm> - <tr> - <td><methodname>void display (float a, int - b){...}</methodname></td> + <glossdef> + <para>Default constructor e.g. <code language="java">obj = new + MyClass()</code>.</para> + </glossdef> + </glossentry> - <td>void</td> + <glossentry> + <glossterm>Non-empty argument list</glossterm> - <td>(float, int)</td> - </tr> - </informaltable> + <glossdef> + <para>Non-default constructor, e.g. <code language="java">obj = + new MyClass("xyz")</code>.</para> + </glossdef> + </glossentry> + </glosslist> </figure> - <figure xml:id="sd1_fig_typeSignatureDetail"> - <title>Defining type signatures</title> + <figure xml:id="sd1_fig_constructorInfo"> + <title>Constructors</title> <itemizedlist> <listitem> - <para>Return type, e.g. <code language="java">void</code></para> + <para>Can only be executed on object creation.</para> </listitem> <listitem> - <para>Number of arguments, e.g. 2.</para> + <para>Are being called prior to any non-constructor method.</para> </listitem> <listitem> - <para>Type of arguments among with their respective order, e.g. - (int, double) differing from (double, int).</para> + <para>Only one of potentially multiple constructors will be + executed exactly one time.</para> </listitem> </itemizedlist> </figure> - <figure xml:id="sd1_fig_methodSignature"> - <title>A method signature</title> - - <para>A method's name and arguments type list:</para> + <figure xml:id="sd1_fig_rectangleThreeConstructors"> + <title>Multiple constructors by overloading</title> <informaltable border="1"> - <colgroup width="75%"/> - - <colgroup width="12%"/> - - <colgroup width="13%"/> - - <tr> - <th valign="top">Method</th> - - <th>Method name</th> - - <th colspan="1">Method signature</th> - </tr> - <tr> - <td><methodname>void print() {...}</methodname></td> - - <td>print</td> + <td valign="top"><programlisting language="java">public class Rectangle { + int width, height; - <td>(void)</td> - </tr> - - <tr> - <td><methodname>int add (int a, int b) {...}</methodname></td> - - <td>add</td> - - <td>(int, int)</td> - </tr> - - <tr> - <td><methodname>int maximum (int a, int b){...}</methodname></td> - - <td>maximum</td> - - <td>(int, int)</td> - </tr> - - <tr> - <td><methodname>void print (int a, float b){...}</methodname></td> - - <td>print</td> - - <td>(int, float)</td> - </tr> - - <tr> - <td><methodname>void display (float a, int - b){...}</methodname></td> - - <td>display</td> + public Rectangle() { + width = height = 1; + } + public Rectangle(int width, int height){ + this.width = width; + this.height = height; + } + public Rectangle(int widthAndHeight) { + width = height = widthAndHeight; + } +}</programlisting></td> - <td>(float, int)</td> + <td><mediaobject> + <imageobject> + <imagedata fileref="Ref/ObjectsAndClasses/rectangleThreeConstruct.svg" + valign="top"/> + </imageobject> + </mediaobject></td> </tr> </informaltable> </figure> - </section> - - <section xml:id="sd1_sect_methodOverloading"> - <title>Method overloading</title> - <figure xml:id="sd1_fig_overloadingPrinciple"> - <title>Method overloading: Same name, different signature</title> + <figure xml:id="sd1_fig_rectangle_constructorCallsConstructor"> + <title>Constructor calls within constructor</title> - <informaltable border="0"> + <informaltable border="1"> <tr> - <td rowspan="2" valign="top"><programlisting language="java">public class Print { - public void print() { // (void) - System.out.println("No argument"); - } - public void print(int i) { // (int) - System.out.println("int value " + i); + <td valign="top"><programlisting language="java">public class Rectangle { + int width, height; + + public Rectangle(int width, + int height){ + this.width = width; + this.height = height; } - public void print(double d) { // (double) - System.out.println("double value " + d); + public Rectangle() { + width = height = 1; } - public void print(int i, int j) { // (int, int) - System.out.println("Two int values "+ - i + " and " + j); + public Rectangle( + int widthAndHeight) { + width = height = + widthAndHeight; } }</programlisting></td> - <td valign="top"><programlisting language="java">Print p = new Print(); -p.print(); -p.print(33); -p.print(4.333); -p.print(-1, 7);</programlisting></td> - </tr> + <td><programlisting language="java">public class Rectangle { + int width, height; - <tr> - <td valign="top"><screen>No argument -int value 33 -double value 4.333 -Two int values -1 and 7</screen></td> + public Rectangle(int width, + int height){ + this.width = width; + this.height = height; + } + public Rectangle() { + this(1, 1); <co linkends="sd1_fig_rectangle_constructorCallsConstructor-1" + xml:id="sd1_fig_rectangle_constructorCallsConstructor-1-co"/> + } + public Rectangle( + int widthAndHeight) { + this(widthAndHeight, + widthAndHeight); <co + linkends="sd1_fig_rectangle_constructorCallsConstructor-2" + xml:id="sd1_fig_rectangle_constructorCallsConstructor-2-co"/> + } +}</programlisting></td> </tr> </informaltable> - </figure> - - <figure xml:id="sd1_fig_overloadingAlternateNames"> - <title>Overloading, alternate names</title> - - <itemizedlist> - <listitem> - <para>Static polymorphism.</para> - </listitem> - <listitem> - <para>Compile time binding.</para> - </listitem> + <calloutlist role="slideExclude"> + <callout arearefs="sd1_fig_rectangle_constructorCallsConstructor-1-co" + xml:id="sd1_fig_rectangle_constructorCallsConstructor-1"> + <para>Reusing constructor <methodname>Rectangle(int width, int + height)</methodname> with parameters <code language="java">width = + height = 1</code>.</para> + </callout> - <listitem> - <para>Early binding.</para> - </listitem> - </itemizedlist> + <callout arearefs="sd1_fig_rectangle_constructorCallsConstructor-2-co" + xml:id="sd1_fig_rectangle_constructorCallsConstructor-2"> + <para>Reusing constructor <methodname>Rectangle(int width, int + height)</methodname> with parameters <code language="java">width = + height = widthAndHeight</code>.</para> + </callout> + </calloutlist> </figure> - <figure xml:id="sd1_fig_noOverloadingInC"> - <title>No such concept in C</title> - - <programlisting language="c">void print() { - printf("No argument\n"); -} + <figure xml:id="sd1_fig_rectangleThreeConstructorsInstances"> + <title>Instances by overloaded constructors</title> -void print(int i) { <emphasis role="bold"> /* Error: redefinition of ‘print’ */</emphasis> - printf("int value %d\n", i); -} + <informaltable border="1"> + <tr> + <td valign="top"><programlisting language="java">Rectangle standard = new Rectangle(); // 1 x 1 +Rectangle square = new Rectangle(2); // 2 x 2 +Rectangle individual = new Rectangle(2, 7); // 2 x 7</programlisting></td> -void main(void) { - print(); - print(33); -}</programlisting> + <td valign="top"><mediaobject> + <imageobject> + <imagedata fileref="Ref/ObjectsAndClasses/rectangleThreeConstruct.svg"/> + </imageobject> + </mediaobject></td> + </tr> + </informaltable> </figure> - <figure xml:id="sd1_fig_distinctReturnType"> - <title>What about return type?</title> - - <programlisting language="java">public class Person { - String getDetails() { return "dummy";} - int getDetails() { return 1;} // Error: 'getDetails()' is already - // defined in 'Person' -}</programlisting> + <figure xml:id="sd1_fig_createRectangleNoConstructor"> + <title>No constructor <abbrev>vs.</abbrev> default constructor</title> <informaltable border="1"> <tr> - <th rowspan="2" valign="top">Return type</th> - - <th colspan="2">Method signature</th> + <th colspan="2">Equivalent: <code language="java">Rectangle r = + new Rectangle();</code></th> </tr> <tr> - <th>Method name</th> + <td valign="top"><programlisting language="java">public class Rectangle { + int width, height; + boolean hasSolidBorder; - <th>Argument type list</th> + // Default constructor, empty body. + public Rectangle ( ){} +}</programlisting></td> + + <td valign="top"><programlisting language="java">public class Rectangle { + int width, height; + boolean hasSolidBorder; +}</programlisting></td> </tr> + </informaltable> + </figure> + <figure xml:id="sd1_fig_createRectangleMissingDefaultConstructor"> + <title>Absent default constructor</title> + + <informaltable border="1"> <tr> - <td>String</td> + <td rowspan="2"><programlisting language="java">public class Rectangle { + int width, height; + boolean hasSolidBorder; - <td>getDetails</td> + public Rectangle(int width, + int height, + boolean hasSolidBorder){ + this.width = width; + this.height = height; + this.hasSolidBorder = + hasSolidBorder; + } +}</programlisting></td> - <td>(void)</td> + <td valign="top"><programlisting language="java">Rectangle r = + new Rectangle(3, 6, false);</programlisting><para>o.K.: Using non-default + constructor.</para></td> </tr> <tr> - <td>int</td> - - <td>getDetails</td> - - <td>(void)</td> + <td valign="top"><programlisting language="java">Rectangle r = new Rectangle();</programlisting><para>Wrong: + Default constructor undefined, but non-default constructor + present.</para></td> </tr> </informaltable> - - <para>Return type irrelevant, only method signatures in <xref - linkend="glo_Java"/>.</para> </figure> - <figure xml:id="sd1_fig_methodSignatureRatio"> - <title>Method signatures rationale</title> + <qandaset defaultlabel="qanda" xml:id="sd1_qanda_geometry_Rectangle"> + <title>Modeling geometry objects: Rectangles</title> - <para>In <xref linkend="glo_Java"/> method signatures allow for - uniquely addressing a method within a given class e.g.:</para> + <qandaentry> + <question> + <para>We want to represent rectangles being defined by width and + height to allow for the subsequently demonstrated + operations:</para> - <para>The method named <code language="java">print</code> having an - int argument followed by a double:</para> + <programlisting language="java">final Rectangle r = new Rectangle(8, 5); <co + linkends="sw1CalloutRectangle-1" xml:id="constructor"/> - <programlisting language="java">print(int, double)</programlisting> - </figure> +System.out.println("Perimeter:" + r.getPerimeter()<co + linkends="sw1CalloutRectangle-2" xml:id="getPerimeter"/>); +System.out.println("Area:" + r.getArea()<co linkends="sw1CalloutRectangle-3" + xml:id="getArea"/>); - <figure xml:id="sd1_fig_chooseByMethodSignature"> - <title>Method signatures rationale</title> +r.setWidth(4); <co linkends="sw1CalloutRectangle-4" xml:id="setWidth"/> +r.setHeight(7); - <mediaobject> - <imageobject> - <imagedata fileref="Ref/ObjectsAndClasses/chooseOverloaded.svg"/> - </imageobject> - </mediaobject> - </figure> +System.out.println("Perimeter:" + r.getPerimeter()); <co + linkends="sw1CalloutRectangle-5" + xml:id="sw1CalloutRectangle-5-co"/> +System.out.println("Area:" + r.getArea());</programlisting> - <figure xml:id="sd1_fig_sysoutPrintlnOverload"> - <title>Example: System.out.print(...)</title> + <calloutlist> + <callout arearefs="constructor" xml:id="sw1CalloutRectangle-1"> + <para>Creating an instance of class + <classname>Rectangle</classname> by calling a non-default + constructor which allows for providing width (8) and height + (5).</para> + </callout> - <informaltable border="0"> - <tr> - <td><methodname - xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-boolean-">print(boolean - b)</methodname></td> - - <td><methodname - xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-char-">print(char - c)</methodname></td> - </tr> - - <tr> - <td><methodname - xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-char:A-">print(char[] - s)</methodname></td> - - <td><methodname - xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-double-">print(double - d)</methodname></td> - </tr> - - <tr> - <td><methodname - xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-float-">print(float - f)</methodname></td> + <callout arearefs="getPerimeter" xml:id="sw1CalloutRectangle-2"> + <para>Returning the rectangle's perimeter,</para> + </callout> - <td><methodname - xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-int-">print(int - i)</methodname></td> - </tr> + <callout arearefs="getArea" xml:id="sw1CalloutRectangle-3"> + <para>Returning the rectangle's area.</para> + </callout> - <tr> - <td><methodname - xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-long-">print(long - l)</methodname></td> + <callout arearefs="setWidth" xml:id="sw1CalloutRectangle-4"> + <para>Setting with and height to new values.</para> + </callout> - <td><methodname - xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-java.lang.Object-">print(Object - obj)</methodname></td> - </tr> + <callout arearefs="sw1CalloutRectangle-5-co" + xml:id="sw1CalloutRectangle-5"> + <para>Write (possibly) changed perimeter and area + values.</para> + </callout> + </calloutlist> - <tr> - <td><methodname - xlink:href="https://docs.oracle.com/javase/10/docs/api/java/io/PrintStream.html#print-java.lang.String-">print(String - s)</methodname></td> + <para>You may start from the following + <classname>Rectangle</classname> class dummy + implementation:</para> - <td/> - </tr> - </informaltable> - </figure> - </section> + <programlisting language="java">/** + * Representing rectangular shapes. + * + */ +public class Rectangle { - <section xml:id="sd1_sect_constructors"> - <title>Constructors</title> + /** + * + * @param width The rectangle's width + * @param heigth The rectangle's height + */ + public Rectangle (double width, double heigth) { + //TODO + } + /** + * @return The rectangle's area. + */ + public double getArea() { + return 0; // TODO + } - <figure xml:id="sd1_fig_createRectangleConstructor"> - <title>Creating and initializing rectangles</title> + /** + * @return The rectangle's perimeter. + */ + public double getPerimeter() { + return 0; // TODO + } - <informaltable border="1"> - <colgroup width="30%"/> + /** + * @return The rectangle's width. + */ + public double getWidth() { + return 0; // TODO + } + /** + * @param width The rectangle's new width + */ + public void setWidth(double width) { + // TODO + } - <colgroup width="70%"/> + /** + * @return The rectangle's height. + */ + public double getHeight() { + return 0; // TODO + } - <tr> - <td valign="top"><programlisting language="java">int a; -a = 33;</programlisting></td> + /** + * @param height The rectangle's new height + */ + public void setHeight(double height) { + // TODO + } +}</programlisting> + </question> - <td valign="top"><programlisting language="java">Rectangle r = new Rectangle(); + <answer> + <para>First we define two instance variables <code + language="java">width</code> and <code + language="java">height</code> representing a + <classname>Rectangle</classname>'s corresponding two parameters + <code language="java">width</code> and <code + language="java">height</code>:</para> -r.width = 28; -r.height = 10; -r.hasSolidBorder = false;</programlisting></td> - </tr> + <programlisting language="java">public class Rectangle { - <tr> - <th colspan="2"><para>Combining statements desired:</para></th> - </tr> + // Instance variables representing a rectangle's parameters + private double <emphasis role="bold">width</emphasis>, <emphasis role="bold">height</emphasis>; +... +}</programlisting> - <tr> - <td valign="top"><programlisting language="java">int a = 33; // works!</programlisting></td> + <para>Next we allow for changing these two parameters:</para> - <td valign="top"><programlisting language="java">Rectangle r = new Rectangle(28, 10, false); // <emphasis - role="red">how ???</emphasis></programlisting></td> - </tr> - </informaltable> + <programlisting language="java">public class Rectangle { - <para>How to get this work?</para> - </figure> + // Instance variables representing a rectangle's parameters + private double width, height; - <figure xml:id="sd1_fig_createRectangleDefineConstruct"> - <title>Defining a constructor</title> +... + /** + * @param width Changing the rectangle's width + */ + public void setWidth(double w) { + <emphasis role="bold">width = w;</emphasis> + } - <programlisting language="java">public class Rectangle { - int width, height; - boolean hasSolidBorder; - ... - public <co linkends="sd1_callout_defineConstructor-1" - xml:id="sd1_callout_defineConstructor-1-co"/> Rectangle <co - linkends="sd1_callout_defineConstructor-2" - xml:id="sd1_callout_defineConstructor-2-co"/> (int width, int height, boolean hasSolidBorder){ - this.width = width; - this.height = height; - this.hasSolidBorder = hasSolidBorder; - } + /** + * @param width Changing the rectangle's height + */ + public void setHeight(double height) { + <emphasis role="bold">this.height = height;</emphasis> + } +... }</programlisting> - </figure> - <para>Similar to <xref linkend="fig_methodSyntax"/> but:</para> - - <calloutlist> - <callout arearefs="sd1_callout_defineConstructor-1-co" - xml:id="sd1_callout_defineConstructor-1"> - <para>No return type declaration.</para> - </callout> + <para>Note the subtle implementation difference between + <methodname>setWidth(...)</methodname> and + <methodname>setHeight(...)</methodname>:</para> - <callout arearefs="sd1_callout_defineConstructor-2-co" - xml:id="sd1_callout_defineConstructor-2"> - <para>Constructor's name equals class name.</para> - </callout> - </calloutlist> + <glosslist> + <glossentry xml:id="glossMethodDiff1"> + <glossterm><methodname>setWidth(double + w)</methodname></glossterm> - <figure xml:id="sd1_fig_constructorSyntax"> - <title>Constructor syntax</title> + <glossdef> + <para>We use the formal parameter name <quote>w</quote>. Its + name does not conflict with the instance variable name + <quote>width</quote> being defined at class level. We can + simply assign this value to our corresponding instance + variable using <code language="java">width = + w;</code>.</para> + </glossdef> + </glossentry> - <programlisting language="java">constructorName (listOfArguments) { - [constructor body] -}</programlisting> + <glossentry xml:id="xmlMethodDiff2"> + <glossterm><methodname>setHeight(double + height)</methodname></glossterm> - <glosslist> - <glossentry> - <glossterm>Empty argument list</glossterm> + <glossdef> + <para>The method's formal parameter <quote>height</quote> + shadows the instance variable's name being defined at class + level. We need the <quote>this</quote> keyword in <code + language="java">this.height = height</code> to resolve the + ambiguity.</para> + </glossdef> + </glossentry> + </glosslist> - <glossdef> - <para>Default constructor e.g. <code language="java">obj = new - MyClass()</code>.</para> - </glossdef> - </glossentry> + <para>Both ways are perfectly legal. The complete implementation + including all remaining methods reads:</para> - <glossentry> - <glossterm>Non-empty argument list</glossterm> + <programlisting language="java">/** + * Representing rectangular shapes. + * + */ +public class Rectangle { - <glossdef> - <para>Non-default constructor, e.g. <code language="java">obj = - new MyClass("xyz")</code>.</para> - </glossdef> - </glossentry> - </glosslist> - </figure> + // Instance variables representing a rectangle's parameters + private double width, height; - <figure xml:id="sd1_fig_constructorInfo"> - <title>Constructors</title> + /** + * + * @param width The rectangle's width + * @param heigth The rectangle's height + */ + public Rectangle (double width, double height) { + setWidth(width); + setHeight(height); + } + /** + * @return The rectangle's area. + */ + public double getArea() { + return width * height; + } - <itemizedlist> - <listitem> - <para>Can only be executed on object creation.</para> - </listitem> + /** + * @return The rectangle's perimeter. + */ + public double getPerimeter() { + return 2 * (width + height); + } - <listitem> - <para>Are being called prior to any non-constructor method.</para> - </listitem> + /** + * @return The rectangle's width. + */ + public double getWidth() { + return width; + } + /** + * @param width The rectangle's new width + */ + public void setWidth(double w) { + width = w; + } - <listitem> - <para>Only one of potentially multiple constructors will be - executed exactly one time.</para> - </listitem> - </itemizedlist> - </figure> + /** + * @return The rectangle's height. + */ + public double getHeight() { + return height; + } - <figure xml:id="sd1_fig_rectangleThreeConstructors"> - <title>Multiple constructors by overloading</title> + /** + * @param width The rectangle's new height + */ + public void setHeight(double height) { + this.height = height; + } +}</programlisting> + </answer> + </qandaentry> + </qandaset> - <informaltable border="1"> - <tr> - <td valign="top"><programlisting language="java">public class Rectangle { - int width, height; + <qandaset defaultlabel="qanda" xml:id="qandasetGeometry"> + <title>Modeling circles</title> - public Rectangle() { - width = height = 1; - } - public Rectangle(int width, int height){ - this.width = width; - this.height = height; - } - public Rectangle(int widthAndHeight) { - width = height = widthAndHeight; - } -}</programlisting></td> + <qandadiv> + <qandaentry> + <question> + <para>This exercise is very similar to <xref + linkend="sd1_qanda_geometry_Rectangle"/>. With respect to the + upcoming section on inheritance its presence will be justified + later by <xref linkend="sw1SectGeometryInherit"/>.</para> - <td><mediaobject> - <imageobject> - <imagedata fileref="Ref/ObjectsAndClasses/rectangleThreeConstruct.svg" - valign="top"/> - </imageobject> - </mediaobject></td> - </tr> - </informaltable> - </figure> + <para>We provide a corresponding class + <classname>Circle</classname> dummy implementation:</para> - <figure xml:id="sd1_fig_rectangle_constructorCallsConstructor"> - <title>Constructor calls within constructor</title> + <programlisting language="java">package step1.dummy; - <informaltable border="1"> - <tr> - <td valign="top"><programlisting language="java">public class Rectangle { - int width, height; +/** + * A circle of given radius + * + */ +public class Circle { - public Rectangle(int width, - int height){ - this.width = width; - this.height = height; + /** + * A new circle + * + * @param radius + * The desired radius. + */ + public Circle(double radius) { + // TODO } - public Rectangle() { - width = height = 1; + + /** + * @return The circle's area. + */ + public double getArea() { + return 0; // TODO } - public Rectangle( - int widthAndHeight) { - width = height = - widthAndHeight; + + /** + * @return The circle's perimeter. + */ + public double getPerimeter() { + return 0; // TODO } -}</programlisting></td> - <td><programlisting language="java">public class Rectangle { - int width, height; + /** + * @return The circle's radius. + */ + public double getRadius() { + return 0; // TODO + } - public Rectangle(int width, - int height){ - this.width = width; - this.height = height; + /** + * @param radius + * Setting the circle's radius to a new value. + */ + public void setRadius(double radius) { + // TODO } - public Rectangle() { - this(1, 1); <co linkends="sd1_fig_rectangle_constructorCallsConstructor-1" - xml:id="sd1_fig_rectangle_constructorCallsConstructor-1-co"/> +}</programlisting> + + <para>Instances of this class shall be usable in the following + fashion:</para> + + <programlisting language="java">public static void main(String[] args) { + final Circle c = new Circle(2.3); + + System.out.println("Radius:" + c.getRadius()); + System.out.println("Perimeter:" + c.getPerimeter()); + System.out.println("Area:" + c.getArea()); + + // Changing the circle's radius to a different value + c.setRadius(4.7); + + System.out.println("Radius:" + c.getRadius()); + System.out.println("Perimeter:" + c.getPerimeter()); + System.out.println("Area:" + c.getArea()); +}</programlisting> + + <para>Hint: Obviously you'll have to define an instance variable + within Circle to keep track of its current radius value. All + methods mentioned above simply depend on this single + value.</para> + </question> + + <answer> + <para>We define an instance variable <code + language="java">radius</code> inside our class + <classname>Circle</classname>:</para> + + <programlisting language="java">public class Circle { + + double radius; +... +}</programlisting> + + <para>Next we implement our method to change a circle's + radius:</para> + + <programlisting language="java">public void setRadius(double r) { + radius = r; +}</programlisting> + + <para>Note that we have chosen a different value for the + method's formal radius parameter to be <quote>r</quote> rather + than <quote>radius</quote>. Many people prefer to use radius + here making it easier for a programmer to recognize the expected + name in the generated <xref linkend="glo_Javadoc"/>:</para> + + <programlisting language="java">public void setRadius(double radius) { +<emphasis role="red"> this.</emphasis>radius = radius; +}</programlisting> + + <para>This requires the usage of the <code + language="java">this</code> keyword to distinguish the formal + parameter in <methodname>setRadius(double radius)</methodname> + from the instance variable previously being defined within our + class <classname>Circle</classname>. In other words: We have to + resolve a name shadowing conflict.</para> + + <para>The rest of the implementation is (quite) straightforward. + A complete class reads:</para> + + <programlisting language="java">package step1; + +/** + * A circle of given radius + * + */ +public class Circle { + + double radius; + + /** + * A new circle + * @param radius The desired radius. + */ + public Circle(double radius) { + setRadius(radius); } - public Rectangle( - int widthAndHeight) { - this(widthAndHeight, - widthAndHeight); <co - linkends="sd1_fig_rectangle_constructorCallsConstructor-2" - xml:id="sd1_fig_rectangle_constructorCallsConstructor-2-co"/> + + /** + * @return The circle's area. + */ + public double getArea() { + return radius * radius * Math.PI; } -}</programlisting></td> - </tr> - </informaltable> - <calloutlist role="slideExclude"> - <callout arearefs="sd1_fig_rectangle_constructorCallsConstructor-1-co" - xml:id="sd1_fig_rectangle_constructorCallsConstructor-1"> - <para>Reusing constructor <methodname>Rectangle(int width, int - height)</methodname> with parameters <code language="java">width = - height = 1</code>.</para> - </callout> + /** + * @return The circle's perimeter. + */ + public double getPerimeter() { + return 2 * Math.PI * radius; + } - <callout arearefs="sd1_fig_rectangle_constructorCallsConstructor-2-co" - xml:id="sd1_fig_rectangle_constructorCallsConstructor-2"> - <para>Reusing constructor <methodname>Rectangle(int width, int - height)</methodname> with parameters <code language="java">width = - height = widthAndHeight</code>.</para> - </callout> - </calloutlist> - </figure> + /** + * @return The circle's radius. + */ + public double getRadius() { + return radius; + } - <figure xml:id="sd1_fig_rectangleThreeConstructorsInstances"> - <title>Instances by overloaded constructors</title> + /** + * @param radius Setting the circle's radius to a new value. + */ + public void setRadius(double radius) { + this.radius = radius; + } +}</programlisting> + </answer> + </qandaentry> + </qandadiv> + </qandaset> - <informaltable border="1"> - <tr> - <td valign="top"><programlisting language="java">Rectangle standard = new Rectangle(); // 1 x 1 -Rectangle square = new Rectangle(2); // 2 x 2 -Rectangle individual = new Rectangle(2, 7); // 2 x 7</programlisting></td> + <qandaset defaultlabel="qanda" xml:id="sdQandaSvgAndTranslation"> + <title>Adding translations and <xref linkend="glo_SVG"/> + export.</title> - <td valign="top"><mediaobject> - <imageobject> - <imagedata fileref="Ref/ObjectsAndClasses/rectangleThreeConstruct.svg"/> - </imageobject> - </mediaobject></td> - </tr> - </informaltable> - </figure> + <qandadiv> + <qandaentry> + <question> + <para>We want to add more features to tour + <classname>Circle</classname> and + <classname>Rectangle</classname> classes:</para> - <figure xml:id="sd1_fig_createRectangleNoConstructor"> - <title>No constructor <abbrev>vs.</abbrev> default constructor</title> + <glosslist> + <glossentry> + <glossterm>Translations</glossterm> - <informaltable border="1"> - <tr> - <th colspan="2">Equivalent: <code language="java">Rectangle r = - new Rectangle();</code></th> - </tr> + <glossdef> + <para>Add two more instance variables x and y and + corresponding setter methods to account for a shape's + translation vector with respect to the origin (0,0). The + following hint may be helpful:</para> - <tr> - <td valign="top"><programlisting language="java">public class Rectangle { - int width, height; - boolean hasSolidBorder; + <programlisting language="java">/** + * @param x The circle's x center coordinate value + */ +public void setX(double x) { + // TODO +} +/** + * @param y The circle's y center coordinate value + */ +public void setY(double y) { + // TODO +}</programlisting> - // Default constructor, empty body. - public Rectangle ( ){} -}</programlisting></td> + <para>You may as well extend the constructors of + <classname>Rectangle</classname> and + <classname>Circle</classname> to accept center coordinates + as well:</para> - <td valign="top"><programlisting language="java">public class Rectangle { - int width, height; - boolean hasSolidBorder; -}</programlisting></td> - </tr> - </informaltable> - </figure> + <programlisting language="java">public class Rectangle { - <figure xml:id="sd1_fig_createRectangleMissingDefaultConstructor"> - <title>Absent default constructor</title> +... + /** + * Rectangle having center coordinates x, y, width and height. + * + * @param x The rectangle center's x-coordinate + * @param y The rectangle center's y-coordinate + * @param width The rectangle's width + * @param height The rectangle's height + */ + public Rectangle(double x, double y, double width, double height) { + ... + } + ... +}</programlisting> - <informaltable border="1"> - <tr> - <td rowspan="2"><programlisting language="java">public class Rectangle { - int width, height; - boolean hasSolidBorder; + <programlisting language="java">public class Circle { + ... - public Rectangle(int width, - int height, - boolean hasSolidBorder){ - this.width = width; - this.height = height; - this.hasSolidBorder = - hasSolidBorder; + /** + * Circle having center coordinates x, y and radius r. + * + * @param x The circle center's x-coordinate + * @param y The circle center's y-coordinate + * @param radius The circle's radius + */ + public Circle(double x, double y, double radius) { + ... + } + ... +}</programlisting> + </glossdef> + </glossentry> + + <glossentry> + <glossterm><xref linkend="glo_SVG"/> export</glossterm> + + <glossdef> + <para>We would like Rectangle and Circle instances to be + visualized as <xref linkend="glo_SVG"/> graphics. <link + xlink:href="http://www.w3schools.com/graphics/svg_examples.asp">SVG + Examples</link> provides editor samples both for <link + xlink:href="http://www.w3schools.com/graphics/svg_circle.asp">circles</link> + and <link + xlink:href="http://www.w3schools.com/graphics/svg_rect.asp">rectangles</link>. + Add a method <methodname>void writeSvg()</methodname> to + both of your classes which allows for <xref + linkend="glo_SVG"/> code being written to standard output. + Use <methodname>System.out.println(...)</methodname> calls + to create the desired <xref linkend="glo_SVG"/> output. + You may need <code language="java">\"</code> to escape + double quotes as in the subsequent example or use single + attribute quotes instead:</para> + + <programlisting language="java">System.out.println("<rect width=\"20\"" ...</programlisting> + </glossdef> + </glossentry> + </glosslist> + + <para>The following code snippet may serve to illustrate the + intended use of <methodname>void writeSvg()</methodname>:</para> + + <programlisting language="java">public class Driver { + + public static void main(String[] args) { + + System.out.println("<!DOCTYPE html><html><body>"); + System.out.println(" <svg width='300' height='200' >"); + + // Draw a rectangle as SVG + final Rectangle r = new Rectangle(5, 4); + r.setX(2); + r.setY(1); + r.writeSvg(); + + // Draw a circle as SVG + final Circle c = new Circle(3); + c.setX(3); + c.setY(1); + c.writeSvg(); + System.out.println(" </svg >"); + System.out.println("</body></html>"); } -}</programlisting></td> +}</programlisting> - <td valign="top"><programlisting language="java">Rectangle r = - new Rectangle(3, 6, false);</programlisting><para>o.K.: Using non-default - constructor.</para></td> - </tr> + <para>Implement the method <methodname>void + writeSvg()</methodname> in both classes + <classname>Rectangle</classname> and + <classname>Circle</classname>. The following sample export is + intended for 300x200 pixel requiring to scale + <abbrev>e.g.</abbrev> the above circle's radius of three by a + factor of 20 resulting in an effective <tag + class="emptytag">circle r='60' ...</tag> value. This scaling is + being required for all parameters:</para> + + <programlisting language="java"><!DOCTYPE html> +<html> + <body> + <svg width='300' height='200' > + <emphasis role="bold"><rect width='100.0' height='80.0' x='40.0' y='20.0' + style='fill:rgb(0,255,0);stroke-width:3;stroke:rgb(0,0,0)'/></emphasis> + <emphasis role="bold"><circle r='60.0' cx='60.0' cy='20.0' + style='fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)'/></emphasis> + </svg > + </body> +</html></programlisting> - <tr> - <td valign="top"><programlisting language="java">Rectangle r = new Rectangle();</programlisting><para>Wrong: - Default constructor undefined, but non-default constructor - present.</para></td> - </tr> - </informaltable> - </figure> + <para>You may copy this output into a file + <filename>svg.html</filename>. A web browser should visualize + this output as:</para> + + <informalfigure> + <mediaobject> + <imageobject> + <imagedata fileref="Ref/Fig/svgGeometry.png"/> + </imageobject> + </mediaobject> + </informalfigure> + </question> + + <answer> + <programlisting language="java">public class Rectangle { + + private double x, y, width, height; + ... + /** + * @param x The rectangle's x center coordinate value + */ + public void setX(double x) { + this.x = x; + } + /** + * @param y The rectangle's y center coordinate value + */ + public void setY(double y) { + this.y = y; + } + +public void writeSvg() { + final int scale = 20; + System.out.println( + "<rect width='" + scale * width +"' height='" + scale * height + + "' x='" + scale * x + "'" + " y='" + scale * y + "'" + + "' style='fill:rgb(0,255,0);stroke-width:3;stroke:rgb(0,0,0)'/>"); + } +}</programlisting> + + <programlisting language="java">public class Circle { + + double x, y, radius; +... + + /** + * @param x The circle's x center coordinate value + */ + public void setX(double x) { + this.x = x; + } + /** + * @param y The circle's y center coordinate value + */ + public void setY(double y) { + this.y = y; + } + +public void writeSvg() { + final int scale = 20; + + System.out.println( + "<circle r='" + scale * radius + + "' cx='" + scale * x + "'" + " cy='" + scale * y + + "' style='fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)'/>"); + + } +}</programlisting> + </answer> + </qandaentry> + </qandadiv> + </qandaset> <qandaset defaultlabel="qanda" xml:id="sd1_qanda_extendEmployee"> <title>Extending the employee example.</title> -- GitLab