[oop] What is the definition of "interface" in object oriented programming

Ok, a friend of mine go back and forth on what "interface" means in programming.

What is the best description of an "interface".

To me an interface is a blueprint of a class, is this the best definition?

This question is related to oop interface definition

The answer is


Interface is a contract you should comply to or given to, depending if you are implementer or a user.


I don't think "blueprint" is a good word to use. A blueprint tells you how to build something. An interface specifically avoids telling you how to build something.

An interface defines how you can interact with a class, i.e. what methods it supports.


Technically, I would describe an interface as a set of ways (methods, properties, accessors... the vocabulary depends on the language you are using) to interact with an object. If an object supports/implements an interface, then you can use all of the ways specified in the interface to interact with this object.

Semantically, an interface could also contain conventions about what you may or may not do (e.g., the order in which you may call the methods) and about what, in return, you may assume about the state of the object given how you interacted so far.


An interface separates out operations on a class from the implementation within. Thus, some implementations may provide for many interfaces.

People would usually describe it as a "contract" for what must be available in the methods of the class.

It is absolutely not a blueprint, since that would also determine implementation. A full class definition could be said to be a blueprint.


A boundary across which two systems communicate.

Interfaces are how some OO languages achieve ad hoc polymorphism. Ad hoc polymorphism is simply functions with the same names operating on different types.


Let us consider a Man(User or an Object) wants some work to be done. He will contact a middle man(Interface) who will be having a contract with the companies(real world objects created using implemented classes). Few types of works will be defined by him which companies will implement and give him results. Each and every company will implement the work in its own way but the result will be same. Like this User will get its work done using an single interface. I think Interface will act as visible part of the systems with few commands which will be defined internally by the implementing inner sub systems.


In my opinion, interface has a broader meaning than the one commonly associated with it in Java. I would define "interface" as a set of available operations with some common functionality, that allow controlling/monitoring a module.

In this definition I try to cover both programatic interfaces, where the client is some module, and human interfaces (GUI for example).

As others already said, an interface always has some contract behind it, in terms of inputs and outputs. The interface does not promise anything about the "how" of the operations; it only guarantees some properties of the outcome, given the current state, the selected operation and its parameters.


As above, synonyms of "contract" and "protocol" are appropriate.

The interface comprises the methods and properties you can expect to be exposed by a class.

So if a class Cheetos Bag implements the Chip Bag interface, you should expect a Cheetos Bag to behave exactly like any other Chip Bag. (That is, expose the .attemptToOpenWithoutSpillingEverywhere() method, etc.)


In short, The basic problem an interface is trying to solve is to separate how we use something from how it is implemented. But you should consider interface is not a contract. Read more here.


In Programming, an interface defines what the behavior a an object will have, but it will not actually specify the behavior. It is a contract, that will guarantee, that a certain class can do something.

Consider this piece of C# code here:

using System;

public interface IGenerate
{
    int Generate();
}

// Dependencies
public class KnownNumber : IGenerate
{
    public int Generate() 
    {
        return 5;
    }   
}

public class SecretNumber : IGenerate
{
    public int Generate()
    {
        return new Random().Next(0, 10);
    }
}

// What you care about
class Game
{
    public Game(IGenerate generator) 
    {
        Console.WriteLine(generator.Generate())
    }
}

new Game(new SecretNumber());
new Game(new KnownNumber());

The Game class requires a secret number. For the sake of testing it, you would like to inject what will be used as a secret number (this principle is called Inversion of Control).

The game class wants to be "open minded" about what will actually create the random number, therefore it will ask in its constructor for "anything, that has a Generate method".

First, the interface specifies, what operations an object will provide. It just contains what it looks like, but no actual implementation is given. This is just the signature of the method. Conventionally, in C# interfaces are prefixed with an I. The classes now implement the IGenerate Interface. This means that the compiler will make sure, that they both have a method, that returns an int and is called Generate. The game now is being called two different object, each of which implementant the correct interface. Other classes would produce an error upon building the code.

Here I noticed the blueprint analogy you used:

A class is commonly seen as a blueprint for an object. An Interface specifies something that a class will need to do, so one could argue that it indeed is just a blueprint for a class, but since a class does not necessarily need an interface, I would argue that this metaphor is breaking. Think of an interface as a contract. The class that "signs it" will be legally required (enforced by the compiler police), to comply to the terms and conditions in the contract. This means that it will have to do, what is specified in the interface.

This is all due to the statically typed nature of some OO languages, as it is the case with Java or C#. In Python on the other hand, another mechanism is used:

import random

# Dependencies
class KnownNumber(object):
    def generate(self):
        return 5

class SecretNumber(object):
    def generate(self):
        return random.randint(0,10)

# What you care about
class SecretGame(object):
    def __init__(self, number_generator):
        number = number_generator.generate()
        print number

Here, none of the classes implement an interface. Python does not care about that, because the SecretGame class will just try to call whatever object is passed in. If the object HAS a generate() method, everything is fine. If it doesn't: KAPUTT! This mistake will not be seen at compile time, but at runtime, so possibly when your program is already deployed and running. C# would notify you way before you came close to that.

The reason this mechanism is used, naively stated, because in OO languages naturally functions aren't first class citizens. As you can see, KnownNumber and SecretNumber contain JUST the functions to generate a number. One does not really need the classes at all. In Python, therefore, one could just throw them away and pick the functions on their own:

# OO Approach
SecretGame(SecretNumber())
SecretGame(KnownNumber())

# Functional Approach

# Dependencies
class SecretGame(object):
    def __init__(self, generate):
        number =  generate()
        print number

SecretGame(lambda: random.randint(0,10))
SecretGame(lambda: 5)

A lambda is just a function, that was declared "in line, as you go". A delegate is just the same in C#:

class Game
{
    public Game(Func<int> generate) 
    {
        Console.WriteLine(generate())
    }
}    

new Game(() => 5);
new Game(() => new Random().Next(0, 10));

Side note: The latter examples were not possible like this up to Java 7. There, Interfaces were your only way of specifying this behavior. However, Java 8 introduced lambda expressions so the C# example can be converted to Java very easily (Func<int> becomes java.util.function.IntSupplier and => becomes ->).


An interface defines what a class that inherits from it must implement. In this way, multiple classes can inherit from an interface, and because of that inherticance, you can

  • be sure that all members of the interface are implemented in the derived class (even if its just to throw an exception)
  • Abstract away the class itself from the caller (cast an instance of a class to the interface, and interact with it without needing to know what the actual derived class IS)

for more info, see this http://msdn.microsoft.com/en-us/library/ms173156.aspx


Conventional Definition - An interface is a contract that specifies the methods which needs to be implemented by the class implementing it.

The Definition of Interface has changed over time. Do you think Interface just have method declarations only ? What about static final variables and what about default definitions after Java 5.

Interfaces were introduced to Java because of the Diamond problem with multiple Inheritance and that's what they actually intend to do.

Interfaces are the constructs that were created to get away with the multiple inheritance problem and can have abstract methods , default definitions and static final variables.

http://www.quora.com/Why-does-Java-allow-static-final-variables-in-interfaces-when-they-are-only-intended-to-be-contracts


Consider the following situation:

You are in the middle of a large, empty room, when a zombie suddenly attacks you.

You have no weapon.

Luckily, a fellow living human is standing in the doorway of the room.

"Quick!" you shout at him. "Throw me something I can hit the zombie with!"

Now consider:
You didn't specify (nor do you care) exactly what your friend will choose to toss;
...But it doesn't matter, as long as:

  • It's something that can be tossed (He can't toss you the sofa)

  • It's something that you can grab hold of (Let's hope he didn't toss a shuriken)

  • It's something you can use to bash the zombie's brains out (That rules out pillows and such)

It doesn't matter whether you get a baseball bat or a hammer -
as long as it implements your three conditions, you're good.

To sum it up:

When you write an interface, you're basically saying: "I need something that..."


Personally I see an interface like a template. If a interface contains the definition for the methods foo() and bar(), then you know every class which uses this interface has the methods foo() and bar().


To me an interface is a blueprint of a class, is this the best definition?

No. A blueprint typically includes the internals. But a interface is purely about what is visible on the outside of a class ... or more accurately, a family of classes that implement the interface.

The interface consists of the signatures of methods and values of constants, and also a (typically informal) "behavioral contract" between classes that implement the interface and others that use it.


Examples related to oop

How to implement a simple scenario the OO way When to use 'raise NotImplementedError'? PHP: cannot declare class because the name is already in use Python class input argument Call an overridden method from super class in typescript Typescript: How to extend two classes? What's the difference between abstraction and encapsulation? An object reference is required to access a non-static member Java Multiple Inheritance Why not inherit from List<T>?

Examples related to interface

Cast object to interface in TypeScript When to use Interface and Model in TypeScript / Angular Is there a way to create interfaces in ES6 / Node 4? Can a normal Class implement multiple interfaces? When to use: Java 8+ interface default method, vs. abstract method How should I have explained the difference between an Interface and an Abstract class? When do I have to use interfaces instead of abstract classes? How to extend a class in python? Interface type check with Typescript Abstract Class vs Interface in C++

Examples related to definition

"Multiple definition", "first defined here" errors SOAP vs REST (differences) Error with multiple definitions of function ReferenceError: variable is not defined C# Foreach statement does not contain public definition for GetEnumerator Add Auto-Increment ID to existing table? How to see the CREATE VIEW code for a view in PostgreSQL? Java: int[] array vs int array[] What is a web service endpoint? What is a "thread" (really)?