Session 6 |
Interfaces
In OOP, it is sometimes helpful to define what a class must do but not how it will do it.
An interface is like a class (a reference type in Java), but it contains abstract methods, constants, default methods and static methods. Method bodies exist only for default methods, private methods and static methods.
A class which implements an interface promises to provide implementations of all abstract methods that are declared in the interface.
A class which implements an interface, inherits and implements all abstract methods of the interface. Thus, an interface dictates what a class must be able to do, but at the same time an interface does not say anything how to do it.
What does it mean - to implement an interface? It means that a class must have keyword implements
in its header and also must provide bodies (implementations) for all abstract methods described in the interface. Each class is free to determine the details of the method implementation. Two classes might implement the same interface in different ways, but each class still supports the same set of methods. Note: If a class does not implement all abstract methods of the interface, the class must declare itself as abstract.
Which classes can implement an interface? Any classes that provide implementation to interface methods can realise an interface. Furthermore, one class can implement any number of interfaces - it assumes that all abstract methods of the corresponding interfaces will be provided with bodies.
What is the advantage of using interfaces? Interfaces and classes that implement interfaces will allow us to conduct similar operations (methods) on objects of different data types.
How to create an interface? 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.
Example
public interface Polygon { // The formula for calculating the area of a polygon depends on the shape of the polygon // The interface says that its implementation should definitely provide details on // how to calculate area and show information on the number of corners, // but does not specify which formula must be used double area(); 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 // It 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; // polymorphism is allowed because Triangle implements Polygon System.out.println(myTriangle.numberOfCorners()); // 3 System.out.println(myPolygon.numberOfCorners()); // 3 myTriangle.output(); // 3 myPolygon.output(); // 3 } }
Note:
- 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);
- objects of an interface data type cannot be created (
new Polygon()
does not compile) because interface methods does not have bodies; objects 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 its superclass and implement methods of interfaces e.g.
class MyFile extends Object implements Input, Output { .. }
; - if a class implements an interface, an instance of the class has several data types - own class data type and the interface data type (e.g. variable
myPolygon
has two data types -Triangle
andPolygon
). This is called polymorphism.
Self-assessment
Unlike inheritance (when a class could inherit fields and methods of one superclass), a class can implement one or more interfaces.
Session 6 |