Newby Coder header banner

Interface

What is an interface in Programming

An interface is like a method (or coded functionality) of a program or application,which is exposed to a user or a client program

The usage of an application for an user or client, is defined by(and limited to) the interface(s) exposed by it

An interface can be a Command Line Interface, like many commands run on a Terminal or windows command line are interfaces of programs,

or a Graphical User Interface, like any Windows or Linux application which has its own window is an interface to its functionalities

Hardware such as keyboard, provides an interface to send data to a computer

Interface in Java

In Java, an interface is a group of methods and constants, which can be implemented by any class

If a class implements an interface, then it has to define all of its methods

A method of an interface is abstract or empty, and its functionality(or body) is defined by the class which implements it

interface BoundedObject {
    float area();
}

Now consider two classes Triangle and Circle, which implement BoundedObject

class Triangle implements BoundedObject {
    float a, b, c;
    public float area() {
        float s = (a + b + c)/3;
        return  java.lang.Math.sqrt(s(s-a)(s-b)(s-c))
    }
}
class Circle implements BoundedObject {
    float r;
    public float area() {
        return  java.lang.Math.PI * r * r;
    }
}

Both classes have to implement method area() as a result, where they calculate area based on their attributes