{"id":201,"date":"2024-07-30T06:50:39","date_gmt":"2024-07-30T06:50:39","guid":{"rendered":"https:\/\/libraryresources.nse.org.ng\/computersciencetwo\/chapter\/abstraction-techniques\/"},"modified":"2026-03-16T14:30:55","modified_gmt":"2026-03-16T14:30:55","slug":"abstraction-techniques","status":"publish","type":"chapter","link":"https:\/\/libraryresources.nse.org.ng\/computersciencetwo\/chapter\/abstraction-techniques\/","title":{"raw":"Abstraction Techniques","rendered":"Abstraction Techniques"},"content":{"raw":"<div class=\"abstraction-techniques\">\n<h3>Interfaces<\/h3>\n<p class=\"import-Normal\">An interface is a class-like construct considered to be a reference type. This means that an object may be of the interface type and referenced as such.<\/p>\n<p class=\"import-Normal\">A Java interface can include any of:<\/p>\n\n<ul>\n \t<li class=\"import-Normal\" style=\"text-indent: 18pt\"><strong>Constants<\/strong>. Fields and their values can be specified. The values are treated as constants - their values cannot be changed. The Java term used to describe something that cannot be altered is final.<\/li>\n \t<li class=\"import-Normal\" style=\"text-indent: 18pt\"><strong>Method signatures.<\/strong> Methods are named, their return type and parameter lists are specified.\n<ul>\n \t<li class=\"import-Normal\" style=\"text-indent: 18pt\"><em>Note: <\/em>Prior to Java 8, these methods could only be abstract. Starting with Java 8, new features like lambda methods required some tweaks to interfaces to allow backwards compatibility with existing interfaces. To allow backwards compatibility, interfaces can now have default methods. However, interfaces are intended to only convey method signatures and leave the implementation up to the implementing class, so the use of default methods should only be used if backwards compatibility is an issue.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p class=\"import-Normal\">An interface thus consists of a set of instance method interfaces, without any associated implementations. A class can implement an interface by providing an implementation for each of the methods specified by the interface. Note that to implement an interface, a class must do more than simply provide an implementation for each method in the interface; it must also <em>state <\/em>that it implements the interface, using the reserved word implements as in this example: \"<code>public class Foo <strong>implements<\/strong> BarInterface<\/code>\". Any concrete class that implements the <code>BarInterface<\/code> interface must provide definitions for each method listed in the interface. We say that an [pb_glossary id=\"246\"]<strong>object<\/strong> [\/pb_glossary]implements an interface if it belongs to a class that implements the interface.<\/p>\n<p class=\"import-Normal\">One of the biggest benefits of using interfaces is their flexibility. A class can implement as many interfaces as it wants, but a class can only extend exactly one class. In fact, a class can both extend one other class and implement one or more interfaces.<\/p>\n<p class=\"import-Normal\">The point of all this is that, although interfaces are not classes, they are something very similar. An interface is very much like an abstract class, that is, a class that can never be used for constructing objects, but can be used as a basis for making [pb_glossary id=\"247\"]subclasses[\/pb_glossary]. The subroutines in an interface are abstract methods, which must be implemented in any concrete class that implements the interface.<\/p>\n\n<h4>Example: Comparable Interface<\/h4>\n<p class=\"import-Normal\"><a class=\"rId150\" href=\"https:\/\/boisestate.hosted.panopto.com\/Panopto\/Pages\/Viewer.aspx?id=623f1f07-b78b-4e56-a548-b11d015835d5\">Lecture: Comparable Comparators (18 minutes)<\/a><\/p>\n<p class=\"import-Normal\">One commonly used interface defined by Java is the <a class=\"rId151\" href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/17\/docs\/api\/java.base\/java\/lang\/Comparable.html\"><strong>Comparable Interface<\/strong><\/a><strong>. <\/strong> This interface contains a single method, <em>compareTo. <\/em> This is the same <em>compareTo<\/em> method that you've used before in the <a class=\"rId152\" href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/17\/docs\/api\/java.base\/java\/lang\/String.html#compareTo(java.lang.String)\">String class<\/a>. Classes that implement <em>Comparable<\/em> are guaranteed to have a <em>compareTo <\/em>method, which is useful for implementing generalized search, sort, min, or max methods.<\/p>\n<p class=\"import-Normal\">Remember from our discussion on polymorphism that an Interface type can be used as a reference type for an object. Thus, you could have a sorting method that can sort any class that implements Comparable. This is exactly how <a class=\"rId153\" href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/17\/docs\/api\/java.base\/java\/util\/Arrays.html#sort(T%5B%5D,int,int,java.util.Comparator)\"><em>Arrays.sort<\/em><\/a> and <a class=\"rId154\" href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/17\/docs\/api\/java.base\/java\/util\/Collections.html#sort(java.util.List)\"><em>Collections.sort<\/em><\/a> is set up.<\/p>\n<p class=\"import-Normal\">Here is the documentation for one of the <a class=\"rId156\" href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/17\/docs\/api\/java.base\/java\/util\/Collections.html#sort(java.util.List)\"><em>Collections.sort<\/em><\/a> methods. We'll discuss this syntax more when we discuss Generic Programming, but this signature says that as long as the elements in the list implement <em>Comparable<\/em>, you can call this sort method on that list.<\/p>\n<p class=\"import-Normal\"><img src=\"https:\/\/libraryresources.nse.org.ng\/wp-content\/uploads\/sites\/21\/2024\/07\/image59-2.png\" alt=\"image\" width=\"1309px\" height=\"909px\"><\/p>\n\n<pre>\n\/\/ Strings are Comparable\nArrayList&lt;String&gt; strList = new ArrayList&lt;String&gt;();\nstrList.add(\"zebra\");\nstrList.add(\"addax\");\nstrList.add(\"black footed ferret\");\nstrList.add(\"koala\");\nCollections.sort(strList);\n\n\/\/ will print in lexicographical order\nSystem.out.println(\"List of Strings:\");\nfor (String animal : strList) {\n    System.out.println(animal);\n}\n\n\/\/ Crates are not Comparable, and so cannot be\n\/\/ sorted\nArrayList&lt;Crate&gt; storage = new ArrayList&lt;Crate&gt;();\nfor (int i = 0; i &lt; strList.size(); i++) {\n   storage.add(new Crate());\n}\n\/\/ Add elements in reverse\nint j = strList.size() - 1;\nfor (int i = 0; i &lt; storage.size(); i++) {\n   storage.get(i).add(strList.get(j));\n j--;\n}\n\n\/\/ Not allowed!\n\/\/ Collections.sort(storage);\nSystem.out.println(\"List of Crates:\");\nfor (Crate elem : storage) {\n   System.out.println(elem.peek());\n}\n\n<\/pre>\n<p class=\"import-Normal\">Note that this interface does not impose any other restrictions whatsoever! As long as the elements implement Comparable and can be compared with each other, you can call sort on your List.<\/p>\n\n<h4>Example: BoxInterface<\/h4>\n<p class=\"import-Normal\">Let's look at a custom interface example. The <em>Boxable <\/em>Interface represents the abstract idea of a box. We can put things in the box, take things out of the box, and look in the box to see what's in the box.<\/p>\n\n<pre>\/**\n* Defines the basic behavior of a box\n*\/\npublic interface Boxable {\n\n   \/**\n   * Adds an element to the Box\n    * @return true if element successfully added; false otherwise\n    *\/\n    public boolean add(String element);\n    \n    \/**\n    * Removes an element from the Box\n    *\/\n    public void remove(String element);\n\n    \/**\n    * @return reference to item in the box\n    *\/\n    public String peek();\n}\n<\/pre>\n<p class=\"import-Normal\">Here's a few examples of classes that implement Boxable. A <a class=\"rId159\" href=\"https:\/\/en.wikipedia.org\/wiki\/Crate\">crate<\/a> is an example of something that probably very closely aligns with your mental image of a box - something hollow in the shape of a square or rectangle with walls.<\/p>\n\n<pre> \n\/**\n* Represents a shipping crate\n*\/\npublic class Crate implements Boxable {\n    private String contents; \/\/ a very small box\n    \n    public Crate() {\n        contents = null;\n    }\n\n    public boolean add(String element) {\n        if (contents == null) {\n            contents = element;\n            return true;\n        }\n        return false;\n    }\n\n    public String remove(String element) {\n        String retVal = null;\n        if (contents != null &amp;&amp; contents.equals(element)) {\n            retVal = contents;\n            contents = null;\n        }\n        return retVal;\n    }\n\n    public String peek() {\n        if (contents == null) {\n            return \"Empty crate\";\n        }\n        return \"Crate contains: \" + contents;\n    }\n}<\/pre>\n<p class=\"import-Normal\">A suitcase, while not typically what you'd call a box, exhibits the behavior of a box. You can put stuff in, take stuff out, and look in it. This shows how an interface only specifies that an object implements specific behaviors, but otherwise the implementing classes don't necessarily need to be otherwise related.<\/p>\n\n<pre>\/**\n * Represents a suitcase\n *\/\n\npublic class Suitcase implements Boxable {\n\n    private String[] contents;\n\n    private int numItems;\n\n    public Suitcase() {\n        \/\/ suitcase has 5 compartments\n        contents = new String[5];\n        numItems = 0;\n    }\n\n    public boolean add(String element) {\n        if (numItems &amp; lt; contents.length) {\n            contents[numItems] = element;\n            numItems++;\n            return true;\n        }\n\n        return false;\n    }\n\n    public String remove(String element) {\n        \/\/ Suitcase is empty\n        if (numItems == 0)\n            return null;\n        \/\/ Find the element to remove\n        int i = 0;\n\n        while (!contents[i].equals(element) &amp; amp; &amp; amp; i &amp; lt; numItems) {\n            i++;\n        }\n        \/\/ If not found, return null\n        if (i == numItems)\n            return null;\n        \/\/ If found, remove element and shift\n        String retVal = contents[i];\n\n        while (i &amp; lt; numItems - 1) {\n            contents[i] = contents[i + 1];\n            i++;\n        }\n\n        return retVal;\n    }\n\n    public String peek() {\n        String res = \"Suitcase compartments contain: \";\n\n        for (String elem: contents) {\n            res += elem + \" \";\n        }\n\n        return res;\n    }\n}\n<\/pre>\nFinally, here's an example of a box that implements both Boxable and Comparable. This object exhibits the behavior of a box and can be sorted! You could create a list of ShippingBoxes and sort them using Collections.sort.\n<pre>\/**\n * Represents a box used for Shipping that can be sorted by weight\n *\n *\/\n\npublic class ShippingBox implements Boxable, Comparable &amp; lt;\nShippingBox &amp; gt; {\n\n    private String item;\n\n    private double maxWeight;\n\n    public ShippingBox(double maxWeight) {\n        this.maxWeight = maxWeight;\n    }\n\n    public boolean add(String element) {\n        if (item == null) {\n            item = element;\n            return true;\n        }\n\n        return false;\n    }\n\n    public String remove(String element) {\n        String retVal = null;\n\n        if (item != null &amp; amp; &amp; amp; item.equals(element)) {\n            retVal = item;\n            item = null;\n        }\n\n        return retVal;\n    }\n\n    public String peek() {\n        if (item == null) {\n            return \"Shipping box is empty\";\n        }\n\n        return \"Shipping: \" + item;\n    }\n    @Override\n\n    public int compareTo(ShippingBox other) {\n        \/\/ close enough to equal\n        if (Math.abs(this.maxWeight - other.maxWeight) &amp; lt; 0.001)\n            return 0;\n        else if (this.maxWeight &amp; gt; other.maxWeight) {\n            return 100; \/\/ return something positive\n        } else {\n            return -100; \/\/ return something negative\n        }\n    }\n}\n<\/pre>\n<h3>Abstract Classes<\/h3>\n<p class=\"import-Normal\">An <strong>abstract class <\/strong>is one that is not used to construct objects, but only as a basis for making subclasses. An abstract class exists <strong>only<\/strong> to express the common properties of all its subclasses. To be an abstract class, the class must contain one or more <strong>abstract methods<\/strong>. The abstract methods in the class are methods for which there is not a reasonable default implementation. Any class that extends an abstract class is required to implement the abstract method(s).<\/p>\n<p class=\"import-Normal\">A class that is not abstract is said to be concrete. You can create objects belonging to a concrete class, but not to an abstract class. A variable whose type is given by an abstract class can only refer to objects that belong to concrete subclasses of the abstract class.<\/p>\n\n<h4>Example: Abstract Box<\/h4>\n<pre>\/**\n * Represents a box that holds one item\n *\/\n\npublic abstract class AbstractBox {\n\n    private double width;\n    private double length;\n    private double height;\n    \/**\n     * Initializes a box with dimensions length x width x height\n     *\/\n    public AbstractBox(double length, double width, double height) {\n        this.length = length;\n        this.width = width;\n        this.height = height;\n    }\n    \n    \/**\n     * Adds element to the box, if it is empty\n     *\n     * @param element\n     * @return true if element was added, false if the box was already full\n     *\/\n    public abstract boolean add(String element);\n\n    \/**\n     * Removes object from the box\n     *\/\n    public abstract String remove();\n\n    @Override\n    public String toString() {\n        String bottom = \"#\".repeat(20) + \"n\";\n        String emptySide = \"###\" + \" \".repeat(14) + \"###\" + \"n\";\n        return emptySide + emptySide + bottom;\n    }\n}<\/pre>\n<p class=\"import-Normal\">Note you cannot create objects of type <em>Box.<\/em> You can, however, use <em>Box<\/em> as a reference type. The following class, <em>MovingBox, <\/em>extends <em>Box<\/em>. Note you can create objects of type <em>MovingBox<\/em> and use reference types of either <em>Box<\/em> or <em>MovingBox<\/em> to refer to a <em>MovingBox<\/em> object.<\/p>\n\n<pre>\/**\n * Represents a box that holds one item\n *\/\n\npublic class MovingBox extends AbstractBox {\n    private String contents;\n    \n    \/**\n     * Initializes a box with dimensions length x width x height\n     *\/\n    public MovingBox(double length, double width, double height) {\n        super(length, width, height);\n        contents = null;\n    }\n    \n    @Override\n    public boolean add(String element) {\n        if (contents != null)\n            return false;\n        contents = element;\n        return true;\n    }\n    \n    @Override\n    public String remove() {\n        return contents;\n    }\n    \n    @Override\n    public String toString() {\n        String inside = String.format(\"### %10s ###n\", contents);\n        return inside + super.toString();\n    }\n}<\/pre>\n<p class=\"import-Normal\">Using the abstract Box class creates a more concrete definition of a box than the interface does. Every class that extends <em>Box<\/em> IS-A box. The abstract class provides specific instance variables and behaviors for most methods as everything (except the constructor) will be inherited by the subclass. Classes that have similar behavior but are not boxes (like a bowl) would not extend Box because a Bowl is not a Box.<\/p>\n\n<h3>Abstract Classes vs. Interfaces<\/h3>\n<p class=\"import-Normal\"><strong>Subclasses <\/strong>(<strong>child classes<\/strong>) have a different relationship between interfaces and abstract <strong>[pb_glossary id=\"248\"]superclasses[\/pb_glossary] (parent classes)<\/strong>. A subclass that implements an interface is saying simply that it \"acts like\" what specified by the interface. The class makes no statements however about fundamentally what it actually is. An actor implements a fearsome alien from a distant planet in one movie and a fickle feline in another. But an actor is actually neither. Just because the actor portrayed an interplanetary alien, doesn't mean that the actor fundamentally possessed all the abilities of such an alien. All it says is that in so far the context in which the actor was utilized as the alien, the actor did implement all the necessary behaviors of the alien.<\/p>\n<p class=\"import-Normal\">A subclass is fundamentally an example of its superclass. A subclass automatically contains all the behaviors of its superclass because it fundamentally <strong>is<\/strong> the superclass. The subclass doesn't have to implement the behaviors of its superclass; it already has them. An actor is a human and by that right, automatically possesses all that which makes up a human: physical characteristics, emotions, ability to critically think, etc. Note that this is true even if the abstract class has 100% abstract methods - it still enforces a strict taxonomical hierarchy.<\/p>\n\n<blockquote>\n<p class=\"import-Normal\" style=\"margin-left: 30pt;margin-right: 30pt;text-indent: 0pt\"><em>implements is about <\/em><strong><em>behaving,<\/em><\/strong><em> extends is about <\/em><strong><em>being<\/em><\/strong><em>.<\/em><\/p>\n<\/blockquote>\n<h3>Generics<\/h3>\n<p class=\"import-Normal\">One of the restrictions of our Box classes is that we are restricting what can be stored in the Box. However, nothing in either the <em>Boxable<\/em> Interface nor the abstract <em>Box<\/em> class actually depends on the type being stored in the Box. That data type can be abstracted away!<\/p>\n<p class=\"import-Normal\">[pb_glossary id=\"241\"]<strong>Generic programming<\/strong> [\/pb_glossary]is one way to allow arbitrary types to be used. Generics allow you to use the algorithm, which is not dependent on the data type, and let the compiler figure out\/handle the actual data being used. We will look at how to implement classes using generic programming in the following sections to expand this definition. But first, let's take a step back and consider how we can classify the Box class(es) - as an [pb_glossary id=\"249\"]Abstract Data Type[\/pb_glossary].<\/p>\n\n<\/div>","rendered":"<div class=\"abstraction-techniques\">\n<h3>Interfaces<\/h3>\n<p class=\"import-Normal\">An interface is a class-like construct considered to be a reference type. This means that an object may be of the interface type and referenced as such.<\/p>\n<p class=\"import-Normal\">A Java interface can include any of:<\/p>\n<ul>\n<li class=\"import-Normal\" style=\"text-indent: 18pt\"><strong>Constants<\/strong>. Fields and their values can be specified. The values are treated as constants &#8211; their values cannot be changed. The Java term used to describe something that cannot be altered is final.<\/li>\n<li class=\"import-Normal\" style=\"text-indent: 18pt\"><strong>Method signatures.<\/strong> Methods are named, their return type and parameter lists are specified.\n<ul>\n<li class=\"import-Normal\" style=\"text-indent: 18pt\"><em>Note: <\/em>Prior to Java 8, these methods could only be abstract. Starting with Java 8, new features like lambda methods required some tweaks to interfaces to allow backwards compatibility with existing interfaces. To allow backwards compatibility, interfaces can now have default methods. However, interfaces are intended to only convey method signatures and leave the implementation up to the implementing class, so the use of default methods should only be used if backwards compatibility is an issue.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p class=\"import-Normal\">An interface thus consists of a set of instance method interfaces, without any associated implementations. A class can implement an interface by providing an implementation for each of the methods specified by the interface. Note that to implement an interface, a class must do more than simply provide an implementation for each method in the interface; it must also <em>state <\/em>that it implements the interface, using the reserved word implements as in this example: &#8220;<code>public class Foo <strong>implements<\/strong> BarInterface<\/code>&#8220;. Any concrete class that implements the <code>BarInterface<\/code> interface must provide definitions for each method listed in the interface. We say that an <a class=\"glossary-term\" aria-haspopup=\"dialog\" aria-describedby=\"definition\" href=\"#term_201_246\"><strong>object<\/strong> <\/a>implements an interface if it belongs to a class that implements the interface.<\/p>\n<p class=\"import-Normal\">One of the biggest benefits of using interfaces is their flexibility. A class can implement as many interfaces as it wants, but a class can only extend exactly one class. In fact, a class can both extend one other class and implement one or more interfaces.<\/p>\n<p class=\"import-Normal\">The point of all this is that, although interfaces are not classes, they are something very similar. An interface is very much like an abstract class, that is, a class that can never be used for constructing objects, but can be used as a basis for making <a class=\"glossary-term\" aria-haspopup=\"dialog\" aria-describedby=\"definition\" href=\"#term_201_247\">subclasses<\/a>. The subroutines in an interface are abstract methods, which must be implemented in any concrete class that implements the interface.<\/p>\n<h4>Example: Comparable Interface<\/h4>\n<p class=\"import-Normal\"><a class=\"rId150\" href=\"https:\/\/boisestate.hosted.panopto.com\/Panopto\/Pages\/Viewer.aspx?id=623f1f07-b78b-4e56-a548-b11d015835d5\">Lecture: Comparable Comparators (18 minutes)<\/a><\/p>\n<p class=\"import-Normal\">One commonly used interface defined by Java is the <a class=\"rId151\" href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/17\/docs\/api\/java.base\/java\/lang\/Comparable.html\"><strong>Comparable Interface<\/strong><\/a><strong>. <\/strong> This interface contains a single method, <em>compareTo. <\/em> This is the same <em>compareTo<\/em> method that you&#8217;ve used before in the <a class=\"rId152\" href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/17\/docs\/api\/java.base\/java\/lang\/String.html#compareTo(java.lang.String)\">String class<\/a>. Classes that implement <em>Comparable<\/em> are guaranteed to have a <em>compareTo <\/em>method, which is useful for implementing generalized search, sort, min, or max methods.<\/p>\n<p class=\"import-Normal\">Remember from our discussion on polymorphism that an Interface type can be used as a reference type for an object. Thus, you could have a sorting method that can sort any class that implements Comparable. This is exactly how <a class=\"rId153\" href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/17\/docs\/api\/java.base\/java\/util\/Arrays.html#sort(T%5B%5D,int,int,java.util.Comparator)\"><em>Arrays.sort<\/em><\/a> and <a class=\"rId154\" href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/17\/docs\/api\/java.base\/java\/util\/Collections.html#sort(java.util.List)\"><em>Collections.sort<\/em><\/a> is set up.<\/p>\n<p class=\"import-Normal\">Here is the documentation for one of the <a class=\"rId156\" href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/17\/docs\/api\/java.base\/java\/util\/Collections.html#sort(java.util.List)\"><em>Collections.sort<\/em><\/a> methods. We&#8217;ll discuss this syntax more when we discuss Generic Programming, but this signature says that as long as the elements in the list implement <em>Comparable<\/em>, you can call this sort method on that list.<\/p>\n<p class=\"import-Normal\"><img decoding=\"async\" src=\"https:\/\/libraryresources.nse.org.ng\/wp-content\/uploads\/sites\/21\/2024\/07\/image59-2.png\" alt=\"image\" width=\"1309px\" height=\"909px\" \/><\/p>\n<pre>\n\/\/ Strings are Comparable\nArrayList&lt;String&gt; strList = new ArrayList&lt;String&gt;();\nstrList.add(\"zebra\");\nstrList.add(\"addax\");\nstrList.add(\"black footed ferret\");\nstrList.add(\"koala\");\nCollections.sort(strList);\n\n\/\/ will print in lexicographical order\nSystem.out.println(\"List of Strings:\");\nfor (String animal : strList) {\n    System.out.println(animal);\n}\n\n\/\/ Crates are not Comparable, and so cannot be\n\/\/ sorted\nArrayList&lt;Crate&gt; storage = new ArrayList&lt;Crate&gt;();\nfor (int i = 0; i &lt; strList.size(); i++) {\n   storage.add(new Crate());\n}\n\/\/ Add elements in reverse\nint j = strList.size() - 1;\nfor (int i = 0; i &lt; storage.size(); i++) {\n   storage.get(i).add(strList.get(j));\n j--;\n}\n\n\/\/ Not allowed!\n\/\/ Collections.sort(storage);\nSystem.out.println(\"List of Crates:\");\nfor (Crate elem : storage) {\n   System.out.println(elem.peek());\n}\n\n<\/pre>\n<p class=\"import-Normal\">Note that this interface does not impose any other restrictions whatsoever! As long as the elements implement Comparable and can be compared with each other, you can call sort on your List.<\/p>\n<h4>Example: BoxInterface<\/h4>\n<p class=\"import-Normal\">Let&#8217;s look at a custom interface example. The <em>Boxable <\/em>Interface represents the abstract idea of a box. We can put things in the box, take things out of the box, and look in the box to see what&#8217;s in the box.<\/p>\n<pre>\/**\n* Defines the basic behavior of a box\n*\/\npublic interface Boxable {\n\n   \/**\n   * Adds an element to the Box\n    * @return true if element successfully added; false otherwise\n    *\/\n    public boolean add(String element);\n    \n    \/**\n    * Removes an element from the Box\n    *\/\n    public void remove(String element);\n\n    \/**\n    * @return reference to item in the box\n    *\/\n    public String peek();\n}\n<\/pre>\n<p class=\"import-Normal\">Here&#8217;s a few examples of classes that implement Boxable. A <a class=\"rId159\" href=\"https:\/\/en.wikipedia.org\/wiki\/Crate\">crate<\/a> is an example of something that probably very closely aligns with your mental image of a box &#8211; something hollow in the shape of a square or rectangle with walls.<\/p>\n<pre> \n\/**\n* Represents a shipping crate\n*\/\npublic class Crate implements Boxable {\n    private String contents; \/\/ a very small box\n    \n    public Crate() {\n        contents = null;\n    }\n\n    public boolean add(String element) {\n        if (contents == null) {\n            contents = element;\n            return true;\n        }\n        return false;\n    }\n\n    public String remove(String element) {\n        String retVal = null;\n        if (contents != null &amp;&amp; contents.equals(element)) {\n            retVal = contents;\n            contents = null;\n        }\n        return retVal;\n    }\n\n    public String peek() {\n        if (contents == null) {\n            return \"Empty crate\";\n        }\n        return \"Crate contains: \" + contents;\n    }\n}<\/pre>\n<p class=\"import-Normal\">A suitcase, while not typically what you&#8217;d call a box, exhibits the behavior of a box. You can put stuff in, take stuff out, and look in it. This shows how an interface only specifies that an object implements specific behaviors, but otherwise the implementing classes don&#8217;t necessarily need to be otherwise related.<\/p>\n<pre>\/**\n * Represents a suitcase\n *\/\n\npublic class Suitcase implements Boxable {\n\n    private String[] contents;\n\n    private int numItems;\n\n    public Suitcase() {\n        \/\/ suitcase has 5 compartments\n        contents = new String[5];\n        numItems = 0;\n    }\n\n    public boolean add(String element) {\n        if (numItems &amp; lt; contents.length) {\n            contents[numItems] = element;\n            numItems++;\n            return true;\n        }\n\n        return false;\n    }\n\n    public String remove(String element) {\n        \/\/ Suitcase is empty\n        if (numItems == 0)\n            return null;\n        \/\/ Find the element to remove\n        int i = 0;\n\n        while (!contents[i].equals(element) &amp; amp; &amp; amp; i &amp; lt; numItems) {\n            i++;\n        }\n        \/\/ If not found, return null\n        if (i == numItems)\n            return null;\n        \/\/ If found, remove element and shift\n        String retVal = contents[i];\n\n        while (i &amp; lt; numItems - 1) {\n            contents[i] = contents[i + 1];\n            i++;\n        }\n\n        return retVal;\n    }\n\n    public String peek() {\n        String res = \"Suitcase compartments contain: \";\n\n        for (String elem: contents) {\n            res += elem + \" \";\n        }\n\n        return res;\n    }\n}\n<\/pre>\n<p>Finally, here&#8217;s an example of a box that implements both Boxable and Comparable. This object exhibits the behavior of a box and can be sorted! You could create a list of ShippingBoxes and sort them using Collections.sort.<\/p>\n<pre>\/**\n * Represents a box used for Shipping that can be sorted by weight\n *\n *\/\n\npublic class ShippingBox implements Boxable, Comparable &amp; lt;\nShippingBox &amp; gt; {\n\n    private String item;\n\n    private double maxWeight;\n\n    public ShippingBox(double maxWeight) {\n        this.maxWeight = maxWeight;\n    }\n\n    public boolean add(String element) {\n        if (item == null) {\n            item = element;\n            return true;\n        }\n\n        return false;\n    }\n\n    public String remove(String element) {\n        String retVal = null;\n\n        if (item != null &amp; amp; &amp; amp; item.equals(element)) {\n            retVal = item;\n            item = null;\n        }\n\n        return retVal;\n    }\n\n    public String peek() {\n        if (item == null) {\n            return \"Shipping box is empty\";\n        }\n\n        return \"Shipping: \" + item;\n    }\n    @Override\n\n    public int compareTo(ShippingBox other) {\n        \/\/ close enough to equal\n        if (Math.abs(this.maxWeight - other.maxWeight) &amp; lt; 0.001)\n            return 0;\n        else if (this.maxWeight &amp; gt; other.maxWeight) {\n            return 100; \/\/ return something positive\n        } else {\n            return -100; \/\/ return something negative\n        }\n    }\n}\n<\/pre>\n<h3>Abstract Classes<\/h3>\n<p class=\"import-Normal\">An <strong>abstract class <\/strong>is one that is not used to construct objects, but only as a basis for making subclasses. An abstract class exists <strong>only<\/strong> to express the common properties of all its subclasses. To be an abstract class, the class must contain one or more <strong>abstract methods<\/strong>. The abstract methods in the class are methods for which there is not a reasonable default implementation. Any class that extends an abstract class is required to implement the abstract method(s).<\/p>\n<p class=\"import-Normal\">A class that is not abstract is said to be concrete. You can create objects belonging to a concrete class, but not to an abstract class. A variable whose type is given by an abstract class can only refer to objects that belong to concrete subclasses of the abstract class.<\/p>\n<h4>Example: Abstract Box<\/h4>\n<pre>\/**\n * Represents a box that holds one item\n *\/\n\npublic abstract class AbstractBox {\n\n    private double width;\n    private double length;\n    private double height;\n    \/**\n     * Initializes a box with dimensions length x width x height\n     *\/\n    public AbstractBox(double length, double width, double height) {\n        this.length = length;\n        this.width = width;\n        this.height = height;\n    }\n    \n    \/**\n     * Adds element to the box, if it is empty\n     *\n     * @param element\n     * @return true if element was added, false if the box was already full\n     *\/\n    public abstract boolean add(String element);\n\n    \/**\n     * Removes object from the box\n     *\/\n    public abstract String remove();\n\n    @Override\n    public String toString() {\n        String bottom = \"#\".repeat(20) + \"n\";\n        String emptySide = \"###\" + \" \".repeat(14) + \"###\" + \"n\";\n        return emptySide + emptySide + bottom;\n    }\n}<\/pre>\n<p class=\"import-Normal\">Note you cannot create objects of type <em>Box.<\/em> You can, however, use <em>Box<\/em> as a reference type. The following class, <em>MovingBox, <\/em>extends <em>Box<\/em>. Note you can create objects of type <em>MovingBox<\/em> and use reference types of either <em>Box<\/em> or <em>MovingBox<\/em> to refer to a <em>MovingBox<\/em> object.<\/p>\n<pre>\/**\n * Represents a box that holds one item\n *\/\n\npublic class MovingBox extends AbstractBox {\n    private String contents;\n    \n    \/**\n     * Initializes a box with dimensions length x width x height\n     *\/\n    public MovingBox(double length, double width, double height) {\n        super(length, width, height);\n        contents = null;\n    }\n    \n    @Override\n    public boolean add(String element) {\n        if (contents != null)\n            return false;\n        contents = element;\n        return true;\n    }\n    \n    @Override\n    public String remove() {\n        return contents;\n    }\n    \n    @Override\n    public String toString() {\n        String inside = String.format(\"### %10s ###n\", contents);\n        return inside + super.toString();\n    }\n}<\/pre>\n<p class=\"import-Normal\">Using the abstract Box class creates a more concrete definition of a box than the interface does. Every class that extends <em>Box<\/em> IS-A box. The abstract class provides specific instance variables and behaviors for most methods as everything (except the constructor) will be inherited by the subclass. Classes that have similar behavior but are not boxes (like a bowl) would not extend Box because a Bowl is not a Box.<\/p>\n<h3>Abstract Classes vs. Interfaces<\/h3>\n<p class=\"import-Normal\"><strong>Subclasses <\/strong>(<strong>child classes<\/strong>) have a different relationship between interfaces and abstract <strong><a class=\"glossary-term\" aria-haspopup=\"dialog\" aria-describedby=\"definition\" href=\"#term_201_248\">superclasses<\/a> (parent classes)<\/strong>. A subclass that implements an interface is saying simply that it &#8220;acts like&#8221; what specified by the interface. The class makes no statements however about fundamentally what it actually is. An actor implements a fearsome alien from a distant planet in one movie and a fickle feline in another. But an actor is actually neither. Just because the actor portrayed an interplanetary alien, doesn&#8217;t mean that the actor fundamentally possessed all the abilities of such an alien. All it says is that in so far the context in which the actor was utilized as the alien, the actor did implement all the necessary behaviors of the alien.<\/p>\n<p class=\"import-Normal\">A subclass is fundamentally an example of its superclass. A subclass automatically contains all the behaviors of its superclass because it fundamentally <strong>is<\/strong> the superclass. The subclass doesn&#8217;t have to implement the behaviors of its superclass; it already has them. An actor is a human and by that right, automatically possesses all that which makes up a human: physical characteristics, emotions, ability to critically think, etc. Note that this is true even if the abstract class has 100% abstract methods &#8211; it still enforces a strict taxonomical hierarchy.<\/p>\n<blockquote>\n<p class=\"import-Normal\" style=\"margin-left: 30pt;margin-right: 30pt;text-indent: 0pt\"><em>implements is about <\/em><strong><em>behaving,<\/em><\/strong><em> extends is about <\/em><strong><em>being<\/em><\/strong><em>.<\/em><\/p>\n<\/blockquote>\n<h3>Generics<\/h3>\n<p class=\"import-Normal\">One of the restrictions of our Box classes is that we are restricting what can be stored in the Box. However, nothing in either the <em>Boxable<\/em> Interface nor the abstract <em>Box<\/em> class actually depends on the type being stored in the Box. That data type can be abstracted away!<\/p>\n<p class=\"import-Normal\"><a class=\"glossary-term\" aria-haspopup=\"dialog\" aria-describedby=\"definition\" href=\"#term_201_241\"><strong>Generic programming<\/strong> <\/a>is one way to allow arbitrary types to be used. Generics allow you to use the algorithm, which is not dependent on the data type, and let the compiler figure out\/handle the actual data being used. We will look at how to implement classes using generic programming in the following sections to expand this definition. But first, let&#8217;s take a step back and consider how we can classify the Box class(es) &#8211; as an <a class=\"glossary-term\" aria-haspopup=\"dialog\" aria-describedby=\"definition\" href=\"#term_201_249\">Abstract Data Type<\/a>.<\/p>\n<\/div>\n<div class=\"glossary\"><span class=\"screen-reader-text\" id=\"definition\">definition<\/span><template id=\"term_201_246\"><div class=\"glossary__definition\" role=\"dialog\" data-id=\"term_201_246\"><div tabindex=\"-1\"><p>An instance of a class, that is, something that is created and takes up storage during the execution of a computer program. In the object-oriented programming paradigm, objects are the basic units of operation. Objects have state in the form of data members, and they know how to perform certain actions (methods).<\/p>\n<\/div><button><span aria-hidden=\"true\">&times;<\/span><span class=\"screen-reader-text\">Close definition<\/span><\/button><\/div><\/template><template id=\"term_201_247\"><div class=\"glossary__definition\" role=\"dialog\" data-id=\"term_201_247\"><div tabindex=\"-1\"><p>In object-oriented programming, any class within a class hierarchy that inherits from some other class. Also known as a child class.<\/p>\n<\/div><button><span aria-hidden=\"true\">&times;<\/span><span class=\"screen-reader-text\">Close definition<\/span><\/button><\/div><\/template><template id=\"term_201_248\"><div class=\"glossary__definition\" role=\"dialog\" data-id=\"term_201_248\"><div tabindex=\"-1\"><p>In object-oriented programming, a class from which another class inherits. Also called a base class or parent class.<\/p>\n<\/div><button><span aria-hidden=\"true\">&times;<\/span><span class=\"screen-reader-text\">Close definition<\/span><\/button><\/div><\/template><template id=\"term_201_241\"><div class=\"glossary__definition\" role=\"dialog\" data-id=\"term_201_241\"><div tabindex=\"-1\"><p>Writing code that will work with various types of data, rather than with just a single type of data. The Java Collection Framework, and classes that use similar techniques, are examples of generic programming in Java.<\/p>\n<\/div><button><span aria-hidden=\"true\">&times;<\/span><span class=\"screen-reader-text\">Close definition<\/span><\/button><\/div><\/template><template id=\"term_201_249\"><div class=\"glossary__definition\" role=\"dialog\" data-id=\"term_201_249\"><div tabindex=\"-1\"><p>Abbreviated ADT. The specification of a data type within some language, independent of an implementation. The interface for the ADT is defined in terms of a type and a set of operations on that type. The behavior of each operation is determined by its inputs and outputs. An ADT does not specify how the data type is implemented. These implementation details are hidden from the user of the ADT and protected from outside access, a concept referred to as encapsulation.<\/p>\n<\/div><button><span aria-hidden=\"true\">&times;<\/span><span class=\"screen-reader-text\">Close definition<\/span><\/button><\/div><\/template><\/div>","protected":false},"author":1,"menu_order":3,"template":"","meta":{"pb_show_title":"","pb_short_title":"","pb_subtitle":"","pb_authors":[],"pb_section_license":""},"chapter-type":[49],"contributor":[],"license":[],"class_list":["post-201","chapter","type-chapter","status-publish","hentry","chapter-type-numberless"],"part":195,"_links":{"self":[{"href":"https:\/\/libraryresources.nse.org.ng\/computersciencetwo\/wp-json\/pressbooks\/v2\/chapters\/201","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/libraryresources.nse.org.ng\/computersciencetwo\/wp-json\/pressbooks\/v2\/chapters"}],"about":[{"href":"https:\/\/libraryresources.nse.org.ng\/computersciencetwo\/wp-json\/wp\/v2\/types\/chapter"}],"author":[{"embeddable":true,"href":"https:\/\/libraryresources.nse.org.ng\/computersciencetwo\/wp-json\/wp\/v2\/users\/1"}],"version-history":[{"count":2,"href":"https:\/\/libraryresources.nse.org.ng\/computersciencetwo\/wp-json\/pressbooks\/v2\/chapters\/201\/revisions"}],"predecessor-version":[{"id":258,"href":"https:\/\/libraryresources.nse.org.ng\/computersciencetwo\/wp-json\/pressbooks\/v2\/chapters\/201\/revisions\/258"}],"part":[{"href":"https:\/\/libraryresources.nse.org.ng\/computersciencetwo\/wp-json\/pressbooks\/v2\/parts\/195"}],"metadata":[{"href":"https:\/\/libraryresources.nse.org.ng\/computersciencetwo\/wp-json\/pressbooks\/v2\/chapters\/201\/metadata\/"}],"wp:attachment":[{"href":"https:\/\/libraryresources.nse.org.ng\/computersciencetwo\/wp-json\/wp\/v2\/media?parent=201"}],"wp:term":[{"taxonomy":"chapter-type","embeddable":true,"href":"https:\/\/libraryresources.nse.org.ng\/computersciencetwo\/wp-json\/pressbooks\/v2\/chapter-type?post=201"},{"taxonomy":"contributor","embeddable":true,"href":"https:\/\/libraryresources.nse.org.ng\/computersciencetwo\/wp-json\/wp\/v2\/contributor?post=201"},{"taxonomy":"license","embeddable":true,"href":"https:\/\/libraryresources.nse.org.ng\/computersciencetwo\/wp-json\/wp\/v2\/license?post=201"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}