I am not sure why an interface
in Java is called an "interface", but I think it can be one of the following two reasons (or both):
Reason one:
This tutorial says the following:
Methods form the object's interface with the outside world
Based on the above quote, I think that the reason why the interface
in Java is called an "interface" is because a Java interface
forces a class that implements that Java interface
to have a certain interface (by "interface" here I don't mean a Java interface
, what I mean is a group of methods, or only one method since a Java interface
can have one or more methods).
Reason two:
The word "interface" in the real world means the following (I got this definition from Google):
a point where two systems, subjects, organizations, etc. meet and interact.
So based on the above definition, I can think of a Java interface
as an entity that sits between two objects, and these two objects communicate with each other through that Java interface
.
For example, imagine that we have a Java interface
called Animal
that have two methods called move()
and makeSound()
, and we have a Cat
class and a Dog
class and both classes implement the Animal
interface.
Now we can do something like this:
Animal animal1 = new Dog();
animal1.makeSound();
We can imagine that animal1.makeSound()
tells the Animal
interface to send a makeSound()
message to the object associated with the Animal
interface (in this case: a Dog
object), the following image demonstrate that:
Now of course the methods of a Java interface
don't have implementations, but I showed that they do in the above image just to show what happens at a conceptual level, and not to show what actually happens (even though I guess theoretically we can have a programming language where the methods of an interface
actually have implementations).
-
Does this answer your question? stackoverflow.com/a/2758619/10585586Rik D– Rik D2020年07月14日 06:57:04 +00:00Commented Jul 14, 2020 at 6:57
-
2Or this? softwareengineering.stackexchange.com/a/339744/320517Rik D– Rik D2020年07月14日 06:57:10 +00:00Commented Jul 14, 2020 at 6:57
-
In programming languages another considered synonym for an interface is contract.πάντα ῥεῖ– πάντα ῥεῖ2020年07月14日 07:46:37 +00:00Commented Jul 14, 2020 at 7:46
-
5Does this answer your question? Why are interfaces in Java called that way?πάντα ῥεῖ– πάντα ῥεῖ2020年07月14日 07:46:58 +00:00Commented Jul 14, 2020 at 7:46
4 Answers 4
A real world analogy
For the sake of keeping the answer simple, let's say that the only cars that exist are personal vehicles with an automatic gearbox, and let's exclude stick shift and larger vehicles such as buses or trucks.
If you have a driver's license, then you are able to drive any car. Even if you learned to drive in a BMW, you'll also be able to drive a Mercedes or a Fiat. Why is that?
Well, simply put, because all these cars have exactly the same layout. Every car implements this same layout, which is why you can change cars and still know exactly how to operate that new car:
- The steering wheel can be turned lef/right to turn the car left/right
- The right pedal makes the vehicle go forward
- The left pedal makes the vehicle stop going forward
- The gear stick allows you to (dis)connect the engine from the wheels
What I have listed here is a complete list of all interactions between a driver and a car that are required for a driver to correctly drive that car.
This "list of possible interactions" is what we call an interface. When you look at both definitions you supplied, you'll see that they fit with my example:
Methods form the object's interface with the outside world
Translated: "Pedals/steering weel/gear stick form the car's interface with the driver".
a point where two systems, subjects, organizations, etc. meet and interact.
The pedals/steering weel/gear stick are the only points where a driver and car interact with one another.
Interfaces in programming
I can think of a Java interface as an entity that sits between two objects
We need to be very careful with our words here. Some real life examples exist where an interface is an object between two actors, e.g. how a translator facilitates communication between two people who speak different languages.
However, in programming terms, the predominant example is where one actor owns another actor, rather than them being two "cooperating" individuals. In this case, the interface is actually referring to (part of) the owned actor itself, rather than a separate layer that sits inbetween them.
Pedantically, your class doesn't need to implement an interface
to "have an interface". Class methods are an "interface" by themselves, as they describe how a consumer can interact with this class.
However, this scenario invariably ties the class and the "interface" together, i.e. this so-called "interface" only applies to this specific class, and each class has its own "interface".
That's not very useful, since it completely excludes the possibility of multiple classes implementing the same interface, similar to how many cars have the exact same layout for the driver.
So instead of letting the class define its own interface, we create a separate interface
, which is often called a "contract", i.e. a list of requirements that a class needs to fulfill if it wants to correctly claim that it implements the interface.
When we have that separate interface, we can then have our classes (however many we want) implement that interface.
A simple example:
public interface ICar
{
void Steer(Direction direction);
void Accelerate();
void Brake();
}
public class BMW318 : ICar
{
public void Steer(Direction direction)
{
// make the car turn in the requested direction
}
public void Accelerate()
{
// make the car accelerate
}
public void Brake()
{
// make the car brake
}
}
public class Fiat500 : ICar
{
public void Steer(Direction direction)
{
// make the car turn in the requested direction
}
public void Accelerate()
{
// make the car accelerate
}
public void Brake()
{
// make the car brake
}
}
To a layman, most cars nowadays seems to be exactly the same, mechanically speaking.If that's how you feel, then the above example doesn't really showcase the power of interfaces.
So I want to take the time here and show you how an interface allows an object to fulfill the same contract but have a completely different implementation:
public class Horse : ICar
{
public void Steer(Direction direction)
{
// pull the reins left/right
}
public void Accelerate()
{
// kick the spurs on the horse
}
public void Brake()
{
// pull the reins and yell "Woah boy!"
}
}
public class Donkey : ICar
{
public void Steer(Direction direction)
{
// pull carrot and stick left/right
}
public void Accelerate()
{
// hold a carrot in front of the donkey
}
public void Brake()
{
// let the donkey eat the carrot
}
}
This Horse
and Donkey
are dramatically different from a BMW318
, yet they still can be operated using the same instructions.
Now that we have these examples, let's showcase the power of an interface in action. The below code works exactly the same for every implementation of ICar
:
public void DriveToTheShop(ICar car)
{
// car is at the house
car.Accelerate();
car.Brake();
car.Steer(Direction.Left);
car.Accelerate();
car.Brake();
// car arrives at the shop
}
This is the power of an interface. We're able to define interactions with an object without even knowing what that object is (is it a car? is it a horse? is it a donkey?). The only requirement we have is that all possible objects (BMW318
, Fiat500
, Horse
, Donkey
) correctly fulfill the interface
that we defined.
Your interpretation of an interface
When you look at this setup, you could say that there are five "things" in the codebase (ICar
, BMW318
, Fiat500
, Horse
, Donkey
). I think you think of an interface
as a separate layer because it is a separate "thing" in the codebase.
I think that what you're intending to say is correct, but the way you are saying it is ambiguous and leaves your words open for an interpretation where it is not correct.
While it is true that the interface
is a separate "thing" in the codebase (which we often refer to as an "abstraction layer"), it's often better to think of the interface as being part of a given implementing class (e.g. Fiat500
), because the class owns its implementation of that interface.
When we're dealing with an object, e.g. a Fiat500
, then the best way to think of it is that the Fiat500
is an ICar
, not that there's a separate ICar
interface.
-
"the interface is actually referring to (part of) the owned actor itself, rather than a separate layer that sits inbetween them" Can I think of it like this: assume that we have a
Cat
class that have the methodsmove()
andmakeSound()
andjump()
. Now when I donew Cat()
by itself (i.e. without assigning the returnedCat
object to a variable), then aCat
object will be created, but thisCat
object will not have an interface (and hence there is no way to access the methods of theCat
object)...Tom– Tom2020年07月17日 04:04:00 +00:00Commented Jul 17, 2020 at 4:04 -
...however, when I do
Cat cat1 = new Cat()
, what will happen here is thatnew Cat()
will create aCat
object without an interface, and then when thisCat
object is assigned tocat1
, then aCat
interface will be added to theCat
object (so theCat
object now consists of two parts: theCat
interface and theCat
implementation). Now assume that theCat
class implements theAnimal
interface (and theAnimal
interface only have the two methodsmove()
andmakeSound()
)...Tom– Tom2020年07月17日 04:04:04 +00:00Commented Jul 17, 2020 at 4:04 -
...now if I do
Animal animal1 = cat1
, then what will happen here is that the interface part of theCat
object will be replaced with the interface ofAnimal
, and so now the two parts that theCat
object consists of are theAnimal
interface and theCat
implementation, and so now even though theCat
object have an implementation for the methodjump()
, I cannot access this method, I can only access the methodsmove()
andmakeSound()
...Tom– Tom2020年07月17日 04:04:50 +00:00Commented Jul 17, 2020 at 4:04 -
...this is because I can only access the
Cat
object through theAnimal
interface (which is now part of theCat
object as I said), and theAnimal
interface only has the methodsmove()
andmakeSound()
. Am I correct?Tom– Tom2020年07月17日 04:04:54 +00:00Commented Jul 17, 2020 at 4:04 -
@Tom. No. You're making it so much more convoluted than it is. When a class implements an interface, any object of that class by definition has that interface. It wouldn't make sense to have an object of a class that doesn't have one of that class' method or properties, right? Well, an interface defines properties and methods, so the same logic applies to interfaces. That's really it. When
Cat : IAnimal
, then everyCat
is anIAnimal
. There's no way of escaping the interface that your class definition defines, when using that class as an object's type.Flater– Flater2020年07月17日 08:43:58 +00:00Commented Jul 17, 2020 at 8:43
The origin of the word interface is quite old since it would date from 1874. Its latin roots mean:
- inter: between (like in inter-action or inter-national)
- facies: the form, the appearance (like in sur-face, or face-to-face when considering human appearance).
Computer science has revived this rather geometrical (or chemical?) term related to "a surface that forms the boundaries between two bodies", by adapting it to the boundaries between hardware (who remembers the shape of an RS232C interface?) or software components.
In component-oriented software in general, and in OOP in particular, the boundaries are defined in terms of what is visible to the outer world for interacting with the component, as opposed to what’s purely internal to the component. The term "interface" was hence naturally adopted by the community.
When James Gosling designed Java, based on C++ roots, he inntended to keep it simple and less error-prone:
In C++, defining an interface requires you to define a class. If you want an abstract interface without any implementation, you need an abstract class with only pure virtual members (if you expect run-time polymorphism). So you quickly end-up with some kind of multiple inheritance, which is difficult to master and very error-prone.
On the other side, having object conforming to an interface for the benefit of code reuse, or object composition, is something semantically different from class inheritance. Decoupling a class from the interfaces it exposes, has hence the benefit of increased simplicity and more precise expressivity.
This lead Gosling to create a new language construct, and the term interface was then quite natural and obvious.
Edit: As Jörg W Mittag points out in the comments, it appears that the feature was not completely new but borrowed from Objective-C's protocols. This doesn't change the explications about the origin of the naming: the interface is the more widely used concept in OOP community. You can for example see in this this 1988 article of the popular DDJ magazine that "interface" was even used to make the term "protocol" in an experimental OOP language more understandable.
-
Especially in C++, non-members can be an integral part of an interface, which actually need not have any class. An
interface
is restricted to members though.Deduplicator– Deduplicator2020年07月14日 14:21:11 +00:00Commented Jul 14, 2020 at 14:21 -
@Deduplicator Thank you for this very interesting and relevant remark.Christophe– Christophe2020年07月14日 14:47:42 +00:00Commented Jul 14, 2020 at 14:47
-
@Christophe: "When James Gosling designed Java, based on C++ roots" – Java is based on Objective-C, not C++. The feature called
interface
in Java is taken directly from Objective-C protocols, which in turn are taken from Smalltalk protocols, which are of course based on the idea of protocols in networking, given the messaging metaphor of OO. Quote: "I'm pretty sure that Java's 'interface' is a direct rip-off of Obj-C's 'protocol' which was largely designed by these ex-NeXT'ers..." and "it has no similarity to C++ as a language."Jörg W Mittag– Jörg W Mittag2020年07月17日 17:51:59 +00:00Commented Jul 17, 2020 at 17:51 -
@JörgWMittag Thanks for this interesting information. Indeed, in his whitepaper on Java Gosling explains how the language has its root in C++ but that the concept of interface is directly inspired from Objective-C's protocols (page 54). No need for guessing: Gosling co-wrote that paper. Funnily, it took me half an hour to find back where I could have found the whitepaper, browsing through dozen of interview, just to find it back on the website of Stroustrup ;-)Christophe– Christophe2020年07月17日 18:44:34 +00:00Commented Jul 17, 2020 at 18:44
-
@JörgWMittag (the fact that interfaces were meant to avoid multiple inheritance as I also claim is documented, page 28) - I made an edit to clarify.Christophe– Christophe2020年07月17日 19:06:32 +00:00Commented Jul 17, 2020 at 19:06
Another word for interface is protocol: The way by which two or more things are to interact.
In essence both of your definitions are correct, and indeed have been implemented in that way across different languages/runtimes.
Every method, property, field, etc.. defined within a class definition is part of the interface that the object provides/Type that the object is. Some of that interface is available to other parts of the software, some of it is purely for the runtime so that it can accurately emulate an Object instance.
Each interface implementation describes a subset of behaviour that should be provided to those who do not wish to deal with an object's totality, merely its compliance to a given protocol.
But these are probably not why interface
is the used keyword. From what I can find on the issue it appears Java borrowed this from Objective-C, although there are numerous older languages that use either the keyword interface
or describe a similar keyword as an interface, such as abstract objects in C++ that have no implementation/data members.
-
1Generally, non-members can also be part of the interface, though not the
interface
.Deduplicator– Deduplicator2020年07月14日 14:16:39 +00:00Commented Jul 14, 2020 at 14:16 -
It is a direct clone of Objective-C protocol. As to why they renamed it, I guess they felt the messaging metaphor for OO would be too confusing to C++ programmers, one of the major target audiences of Java.Jörg W Mittag– Jörg W Mittag2020年07月17日 17:53:57 +00:00Commented Jul 17, 2020 at 17:53
An interface is the part of a system you interact with.
It should be well-designed (easy to use right, hard to misuse or abuse, reasonably easy to implement and test), and well-specified (fully documented, separately from any potential implementation). The importance of having/making good implementations for inspiration and evaluation of the design should also not be underestimated.
Every class
consists of an interface, and its (hidden?) implementation.
As an interface
in Java only consists of the interface part of a class
*, and not also the implementation, that's probably why they chose the name.
Also, it's catchy, and marketing is king.
* Default implementations weakened that though.
-
"Every class consists of an interface, and its (hidden?) implementation" Does that mean that when we do something like this:
Car car1 = new Car();
, then the variablecar1
is considered to be an interface, and theCar
object created usingnew Car()
is the object that is associated with thecar1
interface? and the only way to access thisCar
object is through its interface (which iscar1
)? and so the variablecar1
and theCar
object can be considered to be two separate entities (car1
is an interface entity, and theCar
object is an object entity)?Tom– Tom2020年07月16日 04:19:42 +00:00Commented Jul 16, 2020 at 4:19 -
car1
is a variable, specifically a reference to an object of typeCar
. AndCar
has an interface consisting of all its defined members, which are member- and static- functions and variables, constructors, destructor, and member-types, parent-class and implementedinterface
s, as well as their defined behavior. Due to restrictions of Java there are no non-class entities. The one really unfortunate thing about naminginterface
s that way is the confusion about what an interface is resulting from that choice.Deduplicator– Deduplicator2020年07月16日 10:02:11 +00:00Commented Jul 16, 2020 at 10:02 -
1@Deduplicator: The confusion is especially prevalent with the "Program to an Interface not to an Implementation" maxim from the GoF book. Everybody assumes it is talking about
interface
s when in fact, none of the languages used in the book even has such a feature. I have seen teachers grade well-abstracted, well-factored code badly because it "wasn't programming to an interface" and giving As to other code that simply had anIFoo
for everyFoo
class that was nothing but an exact copy with all method bodies removed for "programming to an interface".Jörg W Mittag– Jörg W Mittag2020年07月18日 06:12:42 +00:00Commented Jul 18, 2020 at 6:12 -
@JörgWMittag It was a fight getting even a hint of that in the tag-wiki here, I gave up on the excerpt. So many rejected edits...Deduplicator– Deduplicator2020年07月18日 11:01:15 +00:00Commented Jul 18, 2020 at 11:01