Implementing An Interface: A Sample Interface, Relatable
Implementing An Interface: A Sample Interface, Relatable
To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can
implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces
implemented by the class. By convention, the implements clause follows the extends clause, if there is one.
If you want to be able to compare the size of similar objects, no matter what they are, the class that instantiates them should
implement Relatable.
Any class can implement Relatable if there is some way to compare the relative "size" of objects instantiated from the class. For
strings, it could be number of characters; for books, it could be number of pages; for students, it could be weight; and so forth. For
planar geometric objects, area would be a good choice (see the RectanglePlus class that follows), while volume would work for
three-dimensional geometric objects. All such classes can implement the isLargerThan() method.
If you know that a class implements Relatable, then you know that you can compare the size of the objects instantiated from that
class.
height = h;
String
Another commonly-used type is String, which represents texts (a sequence of characters) such as "Hello,
world". String is not a primitive type, and will be further elaborated later. In Java, a char is enclosed by
single quotes (e.g., 'A', '0'), while a String is enclosed by double quotes (e.g., "Hello"). For example,
String message = "Hello, world!"; // strings are enclosed in double-quotes
char gender = 'm';
// char is enclosed in single-quotes