Session 6 |
Interfaces
In OOP, it is sometimes helpful to define what a class must do but not how it will do it.
While abstract classes and methods are useful, it is possible to take this concept a step further. In Java, we can fully separate a class’s interface from its implementation by using the keyword interface
.
An interface is a reference type in Java (just like an object class). Syntactically an interface is similar to an abstract class. An interface contains a collection of abstract methods that have no body. A class which implements an interface, inherits and implements the abstract methods of the interface. Thus, an interface specifies what must be done, but not how to do it. Once an interface is defined, any number of classes can implement it. Furthermore, one class can implement any number of interfaces. In the end this will allow us to conduct similar operations (methods) on objects of different data types.
To implement an interface, a class must provide bodies (implementations) for the methods described by the interface. Each class is free to determine the details of its own implementation. Two classes might implement the same interface in different ways, but each class still supports the same set of methods. Thus, code that has knowledge of the interface can use objects of either class since the interface to those objects is the same. By providing the interface
keyword, Java allows us to fully utilize the one interface, multiple methods aspect of polymorphism.
Writing an interface is similar to writing a class. The difference consists in the following: a class describes the attributes and behaviors of an object while an interface contains behaviors that later a class will implement.
Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.
An interface is similar to a class in the following ways:
- an interface can contain any number of methods;
- an interface is written in a file with a .java extension, with the name of the interface matching the name of the file;
- the byte code of an interface appears in a .class file;
- interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.
However, an interface is different from a class in several ways:
- an interface cannot be instantiated;
- an interface does not have any constructors;
- all of the methods in an interface are abstract (excluding default, private and static methods);
- an interface cannot contain instance fields (the only fields that can appear in an interface should be
static
andfinal
); - an interface is not extended by a class; it is implemented by a class.
- an interface can extend multiple interfaces.
Unlike inheritance (when a class could inherit fields and methods of one superclass), a class can implement one or more interfaces.
Syntax
/* File name : InterfaceName.java */ modifier interface InterfaceName { // Any number of final, static fields // Any number of abstract method declarations }
Pay attention:
- modifier public means that the interface is accessible from everywhere and modifier protected means that the interface is accessible within its package;
- an interface is implicitly abstract (we do not need to use the
abstract
keyword in the interface header); - each method in an interface is also implicitly abstract, so the
abstract
keyword is not needed; - methods in an interface are implicitly public;
- variables declared in an interface are not instance variables; instead, they are implicitly
public
,final
, andstatic
and must be initialized.
Interface implementation in classes
Once an interface has been defined, one or more classes can implement that interface. When a class implements an interface, think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.
A class uses implements
keyword to implement an interface. The keyword implements
appears in the class declaration following the extends portion of the declaration.
Example
public interface Polygon { // The formula for calculating the area of a polygon depends on the shape of the polygon // The interface says that an object must have such a method, // but does not specify which formula must be used double area(); // The number of corners in a polygon depends on the shape of the polygon int numberOfCorners(); } public interface Output { // It is not specified if the output is given in the file, command line or somewhere else void output(String myValue); } public class Triangle implements Polygon, Output { private double a, b, c; // legs public Triangle(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } public double area() { // Heron's formula double s = (a + b + c) / 2.0; return Math.sqrt(s * (s - a) * (s - b) * (s - c)); } public int numberOfCorners() { return 3; } public void output(String myText) { System.out.println(myText + " " + numberOfCorners()); } public boolean bolRightAngle() { // In the class, all interface's methods must be implemented // This does not mean that the class cannot have its own methods double[] abc = {a, b, c}; java.util.Arrays.sort(abc); double leg1 = abc[0] * abc[0]; double leg2 = abc[1] * abc[1]; double hypothenuse = abc[2] * abc[2]; return Math.abs(leg1 + leg2 - hypothenuse) < 0.001; // roundoff error } } public class TestClass { public static void main(String[] args) { Triangle myTriangle = new Triangle(3, 4, 5); Polygon myPolygon = myTriangle; // thi is allowed because Triangle implements Polygon System.out.println(myTriangle.numberOfCorners()); // 3 System.out.println(myPolygon.numberOfCorners()); // 3 myTriangle.output(); // 3 myPolygon.output(); // 3 } }
If a class implements an interface, the instance of the class has several data types - own class data type and the interface data type. This is called polymorphism.
Remeber:
- an interface is a data type; this data type can be used by a local variable, an instance, a method etc. (just like in classes);
- interfaces cannot have instances (
new Polygon()
does not compile) because interface methods does not have bodies; instances can be created by subclasses who implement the interface; - several classes can implement the same interface (e.g. Triangle, Rectangle);
- one class can implement several interfaces (the names of the interfaces are delimited by a comma), e.g.
class MyFile implements Input, Output { .. }
; - one class can inherit methods from the superclass and implement methods of interfaces e.g.
class MyFile extends Object implements Input, Output { .. }
.
Java interfaces
java.lang.Comparable
Interface Comparable
has method compareTo
to compare two objects. The interface is used in sorting algorithms. Using different implementations, we can define on what bases the objects are compared and sorted. It is a very important functionality when we want to compare the instances of our own classes. For example, if we want to compare the area of triangles, we have to upgrade Triangle
class as follows:
// upgrade Triangle class with the following lines, the rest leave unchanged public class Triangle implements Polygon, Comparable<Triangle> { public int compareTo(Triangle compareWith) { if (area() < compareWith.area()) return -1; // negative value shows that @@this@@ object is smaller than compareWith if (area() > compareWith.area()) return 1; // positive value indicate that @@this@@ object is larger than compareWith return 0; // zero means that both objects have the same area } }
Useful link: Check API and have a look at methods.
java.util.List
interface List
describes functionality that we already know, e.g. add
, get
and size
. List
is an interface because it is implemented in different classes. For instance, ArrayList
implements a fast search of an element by its index; however, LinkedList
implementation allows a fast insertion and removal of elements by their index.
Useful link: Check API and have a look at methods.
java.lang.Iterable
Iterable
interface describes method iterator
. Iterations are useful for discovering the content of the objects. For example, ArrayList
implements Iterable
interface. In the followinf syntax for (T element : elements)
Java does not control if the elements are placed in an array or a list; it controls if the data type is Iterable
. That means that everyone can create a class whose content can be looked through using for
loop.
Useful link: Check API and have a look at methods.
Session 6 |