<p>I believe that using the term "contract" is hurting more than helping. Most students in that age-range have no personal experience with contracts, so the term is too abstract or remote. Secondly, using contract to "define" the rules for using an interface is likely to lead to a circular definition when you define what a contract is. To increase comprehension for the students it is better to use something they already understand in explaining new concepts.</p>

<p>Using an analogy for how <code>implement</code> in the class declaration relates to the <code>interface</code> you could try using a survey form as an example. A fill-in-the-blank survey has no right or wrong answers, only questions that need an answer, but the answer has to be the right kind. A question about favorite color should not be answered with "scuba diving". If the form has five questions, and only four are answered, it is incomplete and thrown out as unusable, and no credit is given for doing it. In <code>interface</code> declaration is the same way. It lists the methods, their return types and their parameters, but they are blank methods that don't do anything. When the class declaration <code>implements</code> that interface it has to fill in all the blanks and how they are filled in has to match how the interface declared them, the same return type and the same number and type of parameters.</p>

<p>Once they have a grasp on the rules for using interfaces you can use interfaces to explain what a contract is, and how using an interface is part of fulfilling a contract.</p>

CC BY-SA 3.0
2017-06-11T08:59:43.420Z
I like the analogy, but I'm not sure it'll make it clear that `implements` I'd binding
ItamarG3
CC BY-SA 3.0
2017-06-11T09:01:11.090Z
First day of the term, use a survey, with the stated rules that any open blanks on the survey is an error: no credit.
Gypsy Spellweaver
CC BY-SA 3.0
2017-06-11T09:03:27.560Z
So then I could say that the student's answers implements `SurveyAnswer` and as such should contain answers for each question, and of the fitting type?
ItamarG3
CC BY-SA 3.0
2017-06-11T09:20:49.367Z
I don't even like the analogy. I believe this is no more of a contract than using strong types (or a rigorous formatting styles) which permits automated checking for consistency. My view (with zero experience of java) is that an interface definition permits the compiler to tell you when you've made incorrect assumptions. There is no mutually beneficial trade as implied by a true contract.
Sean Houlihane
CC BY-SA 3.0
2017-06-11T13:18:47.070Z
@SeanHoulihane that is not entirely true. There might not be any mutually beneficial trade, but it's not a definition that allows the compiler to know of incorrect assumptions, either. It is a binding construct. But the idea of a contract is useful. I am trying to explain that to the students.
ItamarG3
CC BY-SA 3.0
2017-06-11T13:22:57.957Z
@ItamarGreen, agreed in a formal CS context - but I don't work in that context, and I suspect few of your students understand the word 'contract' in the same way that either of us do. Accepted that Java has some supporting definition, but I dislike it.
Sean Houlihane
CC BY-SA 3.0
2017-06-11T13:42:11.027Z
@SeanHoulihane but this is about formal CS context, o.o... Regardless, You're right that only a few students understand the word contract in that way. That is why I asked this question.
ItamarG3
CC BY-SA 3.0
2017-06-11T08:55:08.397Z
2017-06-11T08:55:08.397Z
Gypsy Spellweaver
<p>This answer draws on Java examples.</p>

<p>I start the interface discussion with a mechanical SATA hard drive in my hand. I discuss the interface called SATA and its universality across devices. I expand this with some digital images of SATA on an optical disc drive as well as a solid state hard drive. Some discussion follows regarding the variety of brands and companies but also the assurance of SATA's common functionality that makes it possible for everyone to play nice together and make reliable components that work across so many devices.</p>

<p>The students verbally list some functions of the SATA interface. I prompt them by asking what all these devices are required to do: read data, write data. Depending how long you want to spend on this and how it matches your curriculum, you get more information from them - what parameters might those functions have etc. Talk about data storage or bits and bytes if its relevant, etc.</p>

<p>All the while, I've listed these functions on the board. Finally, when I think we're done brainstorming, I wrap them in curly brackets and label it an interface. Be careful not to attempt an implementation of any of the functions. That doesn't belong in an interface. (Aside, digging into some Java interface source code, I was surprised to learn of the default function introduced in Java 8 - a lot of things surprised me really when I started digging into the Java source.)</p>

<p>This is my hook for the interface lesson. Next, I jump into all the textbook examples like Edible, Animal, or whatever other abstractions you're going to see at this point in a textbook.</p>

<p>Finally, whether the textbook likes it or not, I slap a Comparable vs Comparator (Java) problem on all of them and make them sort some Geometric objects or something. I spend the next 30 minutes walking around helping students comprehend compiler error messages like "Triangle and Rectangle don't implement the Comparable interface" or "Triangle must implement Comparable.compareTo" or something like that.</p>

<p>Inevitably, many questions about how compareTo works or should work come up. I explain -1, 0, 1 for &lt;, ==, > respectively but then I will show them the source code for java.lang.String or wherever that is, and discuss how Comparable strings actually use the difference between ASCII character codes to compare characters. If not GeometricObjects, ask them how they would sort themselves - height? GPA? grade level? Obviously we need a Comparator for each property if multiple different sorts are needed. It may help to demonstrate that Collections.sort(arrayList) of complex objects won't work with Comparability.</p>

<p>When trying to nail the point, "Always program to an interface," my go-to example is the List interface. I say "Because it's easier to maintain later. If you change the interface, the compiler will require you fix all the implementing classes." I instantiate a few, Vector, LinkedList, ArrayList, with only the interface on the left hand side of the instantiation, List = ArrayList, for example. I show them the source code for the List interface in Java but with Oracle's comments removed so it's just a list of functions. I then show them the same set of common functionality across all implementing classes, only now it's listed in the Eclipse intellisense. This point about always program to an interface is apparently only worth mentioning because those who stay with programming will hear it again some day and you've laid almost a foundation. It's not a point I would spend too much time on with high school students. I drop the phrase and expect they'll hear it again if they carry on with software development.</p>

<p>... and right before I think they get it, time demands that we move on to something else. Hopefully some later assignments revisit the interface.</p>

CC BY-SA 3.0
2017-07-23T04:54:58.233Z
Wow! This is a very good answer. Welcome to [cseducators.se], I hope we'll be hearing more from you.
ItamarG3
CC BY-SA 3.0
2017-07-23T04:11:39.293Z
2017-07-23T05:33:57.853Z
2017-07-23T05:33:57.853Z
ThisClark
<p>I have a bit of a quibble here. The only thing enforced by Java when implementing an interface is the <em>structure</em> of the class implementing it. The intent of the interface programmer isn't enforceable. Good names will help <em>express</em> the intent, but not enforce it. Good javadoc comments will convey more of the intent, but again it isn't enforceable. Absent some compiler/runtime enforcement mechanism of pre and post-conditions and invariants it is pretty unlikely that this will change. </p>

<p>Other languages do, of course, provide such a mechanism which leads to design by contract. </p>

<p>However, what we CAN teach our students is to program to the <em>intent</em> of the code we are working with and not just its structure. And that is always true, not just when implementing an interface. So, In my class the interface of the original post here wouldn't be acceptable, coming without clarifying javadoc comments. It is a contract (only) if you treat it as such. But lots of human interactions are similar. </p>

<p>BTW, students writing subclasses (which IMO is too often done poorly) break the intent of the superclass as well as the structure. Among other things, subclassing by adding public features makes Liskov's Substitution Principle impossible to obey. If you need to <em>cast</em>, your code is probably broken. I'll wait for a good question about subclassing in Java-like languages to talk about why that is. </p>

CC BY-SA 3.0
2017-07-23T11:35:58.307Z
java enforces that an implementing class actually ***`implements`*** the method signatures defined in the interface. Anything that implements a specific interface is promising that you can work and use ***only*** the parts that are from the interface (`Interface objectName = new ImplementingClass()`). At compile time, you can use anything that `Interface` says, but not what `ImplementingClass()` can do which isn't related to the interface. My point is that I'm not sure I understand why you say that `intent` is the only thing enforced.
ItamarG3
CC BY-SA 3.0
2017-07-23T12:11:34.337Z
Declaring variables with the interface type is good style but, unfortunately only style, and that isn't enforced.
Buffy
CC BY-SA 4.0
2018-10-17T21:06:21.683Z
Domain Specific Languages have a lot of advantages and have existed since long before OOP came about. The biggest advantage, from my point of view, is that I can hand over a lot of 'programming' work to non-programmer domain experts, including ordinary folks. My first goal as a programmer is to make my services no longer required. I used to be quite successful at that.
Scott Rowe
CC BY-SA 3.0
2017-07-23T11:20:53.650Z
2017-07-23T11:20:53.650Z
Buffy
<p>I really enjoy the answer to <a href="https://stackoverflow.com/a/14244705/290136">this question</a> provided on StackOverflow and use it as a basic introduction/discussion point in my CS2 course:</p>

<blockquote>
  <p>Consider the following situation:</p>
  
  <blockquote>
    <p><em>You are in the middle of a large, empty room, when a zombie suddenly attacks you.</em></p>
    
    <p><em>You have no weapon.</em></p>
    
    <p><em>Luckily, a fellow living human is standing in the doorway of the room.</em></p>
    
    <p><em>"Quick!" you shout at him. "Throw me something I can hit the zombie with!"</em></p>
  </blockquote>
  
  <p>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:</p>
  
  <p>-It's something that can be tossed (He can't toss you the sofa)</p>
  
  <p>-It's something that you can grab hold of (Let's hope he didn't toss a shuriken)</p>
  
  <p>-It's something you can use to bash the zombie's brains out (That rules out pillows and such)</p>
  
  <p>-It doesn't matter whether you get a baseball bat or a hammer -
  as long as it implements your three conditions, you're good.</p>
  
  <p><strong>To sum it up:</strong></p>
  
  <p>When you write an interface, you're basically saying: "I need something that..."</p>
</blockquote>

CC BY-SA 4.0
2018-10-14T07:52:40.077Z
This is an incredibly simple and very nice answer. Thank you!
ItamarG3
CC BY-SA 4.0
2018-10-14T18:46:18.577Z
@ItamarG3 It also is fun to see how much your students really have thought about the zombie apocalypse... :)
cryptic_star
CC BY-SA 4.0
2018-10-13T21:12:48.810Z
2018-10-14T02:52:29.987Z
2018-10-14T02:52:29.987Z
cryptic_star
<p>An interface "isn't" a contract. But it <em>embodies</em> a contract. Implicitly if not explicitly. </p>

<p>A simple example is when you go to Kinko's (FedEx), and you click on the end of the opening interface that you agree with the terms of use. In turn, Kinko's agrees to provide you with a bunch of computer services, express or implied, for the money you are paying them.</p>

<p>Other interfaces don't necessarily have a paywall, but they usually have terms and conditions (going both ways), plus the requirement that you provide at least a minimum of ID to use them.</p>

CC BY-SA 4.0
2018-10-17T20:39:00.233Z
@SeanHoulihane but I am hoping that FedEx would in fact enforce their conditions, because they don't want an entire truckload or plane cargohold of packages to burn up, whether I cared (or perhaps intended that) or not. Caring to protect yourself and your users is the bottom line.
Scott Rowe
CC BY-SA 4.0
2018-10-18T07:54:02.943Z
@ScottRowe Your desires are irrelevant to the interface. There are implications for misusing the interface, but an interface which includes testing of its inputs is more expensive. Providing an un-validated interface may also be expensive (see GPZ vulnerabilities which use speculation and a cache side-channel) - this is reflected in your risk analysis.
Sean Houlihane
CC BY-SA 3.0
2017-06-11T13:35:22.930Z
[tag:interface] specifically isn't about the **user** interface, it's about the object oriented programming interface.
ItamarG3
CC BY-SA 3.0
2017-06-11T13:48:54.570Z
This analogy works. FedEx ask for payment, a box, and a destination. Whatever is in the box, they'll ship it even if you put perishables in the box (or lithium batteries), and their shipping method isn't appropriate. They don't guarantee the contents arrive unharmed, they just move the box and its contents. Mis-treat an API, and you have a validation problem.
Sean Houlihane
CC BY-SA 3.0
2017-06-11T13:33:47.640Z
2017-06-11T13:33:47.640Z
Tom Au
<p>An interface is an artifact that exists between two or more abstractions. It states <em>what</em> capabilities a given abstraction has to offer its users. It does not say <em>how</em>. The <em>what</em> part is an interface, and the <em>how</em> part is the implementation. <a href="https://blog.pragmaticengineer.com/a-philosophy-of-software-design-review/" rel="nofollow noreferrer">A good interface is deep</a> (the implementation has much more volume than the interface). Its a characteristic that makes it similar to a physical contract.</p>
<p>How does it correspond to an interface? You sign a six-page-long contract - that corresponds to a proportionally small interface of your abstraction. Then you provide your service or a product - that corresponds to a proportionally deep implementation hiding a lot of domain, and contract-specific complexity. The contract not only enforces mutual obligations but also gives you (as a service provider) a lot of freedom in execution, as long as you don’t breach the terms, and meet the essential KPIs.</p>
<p>As real-life contract - an interface is a basis for collaboration. I've written more about the topic <a href="https://medium.com/p/575553dcb6a2" rel="nofollow noreferrer">here</a>.</p>

CC BY-SA 4.0
2022-11-23T13:48:06.277Z
2022-11-23T13:48:06.277Z
Maciek Czarnik
<p>Java (and most other languages) interfaces are not contracts.</p>

<p>The contract on Eat is:</p>

<ul>
<li>I take no data</li>
<li>I return no data</li>
<li>you can call me under any situation</li>
<li>I will not crash/throw (most languages don't even have this)</li>
<li>I will do what ever seem like a good idea to me</li>
</ul>

<p>I.E. there is no contract. They don't see it because it is not there. Without pre and post conditions, there are no promises, there is no contract.</p>

<p>An example of a contract may look like this (I have to make up some syntax).</p>

<pre><code>public interface Edible {

    public boolean isEdible();
    public boolean isEaten();
    public void eat() 
       precondition: isEdible();
       postcondition: isEaten();
    end

    invariant:
       isEaten() implies isEdible();
    end
}
</code></pre>

CC BY-SA 3.0
2017-07-21T20:26:48.870Z
To quote [Oracle](https://docs.oracle.com/javase/tutorial/java/concepts/interface.html) on Interfaces: "Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler." So, it is a contract, in the sense of I'm talking about, which is what I'm asking about. Which is not exactly what you answered. Nevertheless, your comment on my example is useful.
ItamarG3
CC BY-SA 3.0
2017-07-21T20:41:55.750Z
I think oracle (or was it sun micro-systems), read that interfaces form a contract, and then noted that they had something that they called an interface, and then wrongly concluded that they were constructing contracts. This is an easy mistake if they did not know what the original author meant by interface. “an interface is defined in terms of the obligations of the sender and the receiver involved in an interaction. … Typically these are set forth in preconditions and postconditions … invariant conditions.” — B.Meyers (1994)
ctrl-alt-delor
CC BY-SA 3.0
2017-07-21T20:43:16.433Z
that may be. But do you agree that *it* ***can*** *be thought of* as a contract?
ItamarG3
CC BY-SA 3.0
2017-07-21T22:25:56.117Z
@ItamarG3 If a Java interface is a contract, then. What do the two sides in the contract promise? I have around 25 years programming experience, and I can not see it. I would not expect my pupils to see it. Can you explain how Java interfaces are contracts to me.
ctrl-alt-delor
CC BY-SA 3.0
2017-07-23T11:05:35.467Z
@richard, perhaps "intended contract" is a better term. It certainly can't be enforced in Java. But the software is generally better if everyone agrees to behave as if it were.
Buffy
CC BY-SA 3.0
2017-07-23T11:59:58.890Z
@Buffy but where is the behaviour agreed? I can see that you can use good-names, and you could but the contracts into comments. I could agree that this is an implicit contract, if the names are good, e.g. draw_line(start: point, end: point), we would expect this to draw a line, between two points.
ctrl-alt-delor
CC BY-SA 3.0
2017-07-23T12:14:41.213Z
@richard and anything implementing that interface **must** implement `draw_line` method (which means write a method body). Btw, I'm sorry for the confusion. I mistagged the question. Now I see that tagging with [tag:java] is needed.
ItamarG3
CC BY-SA 3.0
2017-07-21T20:23:22.027Z
2017-07-21T22:37:18.953Z
2017-07-21T22:37:18.953Z
ctrl-alt-delor
<p>If I were asked to describe how a pin-and-tumbler lock works - the kind of lock most of the developed world have on their front doors - I cannot imagine that the word &quot;contract&quot; would find its way into the explanation.</p>
<p>This is despite the fact that, if you squint really hard, the relationship between the key (on the one hand) and the keyway and pins (on the other hand) does involve some kind of match, and the existence of the lock and key does in some sense govern the relationship between householder and strangers.</p>
<p>There's probably already a number of people who have no ready idea how pin-and-tumbler locks work to understand this analogy, and many more who would wonder where on Earth I pulled this from.</p>
<p>Likewise, many middle-age adults (let alone high school students) would have no clear idea what a &quot;contract&quot; even is, beyond some kind of lengthy document written in small print, that some corporation imposes on you as part of ordinary and necessary daily dealings <em>in order to evade their legal liabilities</em>.</p>
<p>Even if you ask a lawyer, they'd say a contract involves offer and acceptance, consideration on both sides, an intention to enter legal relations, and so on.</p>
<p>Does any of this seem to have the remotest connection to defining an &quot;interface&quot; in an OO programming language? I would say not.</p>
<p>I think that OO programming is actually very complicated to explain, both in computer science terms, and in terms of a certain philosophy or ideology that is associated with &quot;pure&quot; OO programming.</p>
<p>To add to the hassle, mainstream programming languages are a muddied synthesis of both OO concepts and non-OO concepts (with the non-OO concepts being something that don't reconcile with the OO concepts), and the most compelling demonstrations of the capabilities of OO programming involve software development being done at quite some scale with a division of labour (which is at odds with how most young programmers practice coding, which is as a solitary activity, and at odds with their industrial experience, which is zero).</p>
<p>Quite frankly, I would not even try to teach interfaces to high school students in terms of abstract concepts - unless you're dealing with a classroom of savants.</p>
<p>I would either just declare the concept to be something that is advanced beyond the level of your course, or I would demonstrate some practical examples of how interfaces can be used, without trying to explain their conceptual nature in a generalised fashion.</p>

CC BY-SA 4.0
2022-12-28T19:43:20.373Z
2022-12-28T19:43:20.373Z
Steve
<p>Rather than thinking of motivating examples, I prefer to teach it from the perspective of polymorphism.  The mechanism of polymorphism <strong>requires</strong> an object referenced by a reference of the interface type to have a valid implementation of the method (and implementing the interface allows the compiler to enforce that requirement).  So rather than teaching it as being merely a contract, I teach it as being part of a key mechanism in the Java programming language.  I think it is important that students learn the underlying logic of a programming language and I think it is better to teach the principles rather than just presenting lots of examples and hoping the students will infer the mechanism for themselves (some will, some won't).  Of course you need examples as well, to show the cool stuff you can do with the mechanism.</p>
<p>Of course this isn't the only use for interfaces, but it explains <em>why</em> the interface enforces a contract of sorts.  Those other uses can be explained later, and when you do, the students will already understand that implementing an interface enforces a contract, so they can focus on the new use, rather than the mechanism.</p>

CC BY-SA 4.0
2023-01-03T08:27:07.110Z
2023-01-03T08:27:07.110Z
Dikran Marsupial
<p>A few things jump out from the <a href="https://docs.oracle.com/javase/tutorial/java/concepts/interface.html" rel="noreferrer">official Java documentation</a>:</p>

<p>As far as an example goes, the idea of a Remote as an interface works really well based on this explanation.</p>

<blockquote>
  <p>Methods form the object's <em>interface</em> with the outside world; the
  buttons on the front of your television set, for example, are the
  interface between you and the electrical wiring on the other side of
  its plastic casing. You press the "power" button to turn the
  television on and off.</p>
</blockquote>

<p>Using topics like design or hardware might be a good direction to go since a discussion of UI could build up into a more abstract understanding of the notion of an interface. </p>

<p>It is important to note that this documentation makes use of the same contract analogy you mention:</p>

<blockquote>
  <p>Implementing an interface allows a class to become more formal about
  the behavior it promises to provide. Interfaces form a <em>contract</em> [emphasis added]
  between the class and the outside world, and this contract is enforced
  at build time by the compiler.</p>
</blockquote>

<p>To implement an interface is to promise, to guarantee, that the class will come through on its end of the bargain and implement everything in the interface. The idea of a contract is already a successful analogy, so I wouldn't try to necessarily reinvent the wheel here lest you introduce more confusion with a different analogy. You could have students use the word promise if contractual language does not hit home for them.</p>

<p>Putting it in the context of friendship and promises being made might make them understand an interface in a better way than legal agreements and contracts. Ultimately, simple, relevant examples that clearly illustrate <em>why</em> interfaces are of value and how they are central to human-computer interaction will probably be of more value than a different, clever analogy.</p>

<p>You may find <a href="https://stackoverflow.com/questions/3355408/explaining-interfaces-to-students">this since-closed discussion on SO</a> of value.</p>

CC BY-SA 4.0
2018-10-13T21:11:14.457Z
I just want to add onto this remote example. I did an assignment for class where students were constructing interfaces/classes for a Samsung-esque company. So they had interfaces like `VoiceAssistant` that were then only implemented on some of their classes (e.g., smartphone, smart assistant, but not TVs). The students found it very effective!
cryptic_star
CC BY-SA 3.0
2017-06-11T08:27:49.633Z
The context of friendship sounds potentially useful.
ItamarG3
CC BY-SA 3.0
2017-06-11T07:45:38.010Z
2017-06-11T07:45:38.010Z
Peter
<p>When teaching Interfaces (in Java, for example), it is common to describe them as a contract. Which means that if a class implements an interface, it has to use the methods in the interface. </p>

<p>As an example, the students are shown the following:</p>

<pre><code>public interface Edible {

    public boolean hasNuts();
    public void eat();
}
</code></pre>

<p>and then</p>

<pre><code>public class PeanutbutterSandwich implements Edible {

    //now  we have to implement the methods in Edible
    public boolean hasNuts(){
        return true; //just as an example
    }
    public void eat(){
        if(hasNuts())
            System.out.println("I contain nuts!");
        else
            System.out.println("I don't contain nuts!");
    }
}
</code></pre>

<p>The problem with this example is that students don't always see how the interface acts as a contract. How could I explain the analogy in a better way, maybe with a different example that can show this in a better way?</p>

<p>The students are high school level, and are familiar with polymorphism, but not with abstract classes. </p>

CC BY-SA 3.0
2017-06-11T07:18:14.677Z
At least in this example, consider changing the class Edible to Food. It makes more sense to have the interface name a noun in this context as I see it.
Peter
CC BY-SA 3.0
2017-06-11T07:20:09.993Z
@Peter I thought about it but I feared it was too much like a name I'd give an abstract class. But after more thought, i think it's not as confusing as I thought. Btw, it's not a class, but an interface
ItamarG3
CC BY-SA 3.0
2017-07-21T20:19:41.013Z
The contract on Eat is I take no data, I return no data, you can call me under any situation, and I promise to do what ever I want (your guess is as good as mine as to what I will do). I.E. there is no contract. They don't see it because it is not there. Do design by contract, that has contracts (pre and post conditions).
ctrl-alt-delor
CC BY-SA 4.0
2018-11-15T13:17:19.097Z
`public interface Edible { public boolean isEdible();`  I find this a very bad example for students. If a class has the `Edible` interface, **it is therefore edible**. Not only should the boolean value be irrelevant, it downright contradicts the meaning of assigning an interface to a class ("it is edible because the interface is assigned, but it's not edible because the boolean says it isn't"). In most (common) cases, the fact that you assign the interface is confirmation that the class _is_ "Fooable". If it isn't Fooable, then it shouldn't have the IFooable interface. [..]
Flater
CC BY-SA 4.0
2018-11-15T13:20:23.977Z
[..] It also doesn't make sense to have an `eat()` method for something that's not edible. You're sullying the clear contract by having that boolean in the middle of it. The boolean (when false) can effectively negate the primary reason for the contract to exist in the first place.
Flater
CC BY-SA 4.0
2018-11-17T07:41:03.060Z
@Flater You are quite right. When I wrote this answer more than a year ago, my knowledge of OOP was not as good as it is now. Thank you for bringing this to my attention.
ItamarG3
<secondary-education><java><teaching-analogy><object-oriented-paradigm><interface>
Explaining how an Interface is a contract
# Explaining how an Interface is a contract

(Asked by: username_0 on 2017-06-11)

When teaching Interfaces (in Java, for example), it is common to describe them as a contract. Which means that if a class implements an interface, it has to use the methods in the interface. 
As an example, the students are shown the following:
public interface Edible {

    public boolean hasNuts();
    public void eat();
}

and then
public class PeanutbutterSandwich implements Edible {

    //now  we have to implement the methods in Edible
    public boolean hasNuts(){
        return true; //just as an example
    }
    public void eat(){
        if(hasNuts())
            System.out.println("I contain nuts!");
        else
            System.out.println("I don't contain nuts!");
    }
}

The problem with this example is that students don't always see how the interface acts as a contract. How could I explain the analogy in a better way, maybe with a different example that can show this in a better way?
The students are high school level, and are familiar with polymorphism, but not with abstract classes.

**Tags:** secondary-education, java, teaching-analogy, object-oriented-paradigm, interface

> **Comments:**
> **username_1**: At least in this example, consider changing the class Edible to Food. It makes more sense to have the interface name a noun in this context as I see it.  
> **username_0**: @username_1 I thought about it but I feared it was too much like a name I'd give an abstract class. But after more thought, i think it's not as confusing as I thought. Btw, it's not a class, but an interface  
> **username_2**: The contract on Eat is I take no data, I return no data, you can call me under any situation, and I promise to do what ever I want (your guess is as good as mine as to what I will do). I.E. there is no contract. They don't see it because it is not there. Do design by contract, that has contracts (pre and post conditions).  
> **username_3**: `public interface Edible { public boolean isEdible();`  I find this a very bad example for students. If a class has the `Edible` interface, **it is therefore edible**. Not only should the boolean value be irrelevant, it downright contradicts the meaning of assigning an interface to a class ("it is edible because the interface is assigned, but it's not edible because the boolean says it isn't"). In most (common) cases, the fact that you assign the interface is confirmation that the class _is_ "Fooable". If it isn't Fooable, then it shouldn't have the IFooable interface. [..]  
> **username_3**: [..] It also doesn't make sense to have an `eat()` method for something that's not edible. You're sullying the clear contract by having that boolean in the middle of it. The boolean (when false) can effectively negate the primary reason for the contract to exist in the first place.  
> **username_0**: @username_3 You are quite right. When I wrote this answer more than a year ago, my knowledge of OOP was not as good as it is now. Thank you for bringing this to my attention.  

---

## 10 answers

### Answer by username_1 on 2017-06-11. Score: 8 | Accepted answer

A few things jump out from the [official Java documentation](https://docs.oracle.com/javase/tutorial/java/concepts/interface.html):

As far as an example goes, the idea of a Remote as an interface works really well based on this explanation.

> Methods form the object's *interface* with the outside world; the
> buttons on the front of your television set, for example, are the
> interface between you and the electrical wiring on the other side of
> its plastic casing. You press the "power" button to turn the
> television on and off.

Using topics like design or hardware might be a good direction to go since a discussion of UI could build up into a more abstract understanding of the notion of an interface.

It is important to note that this documentation makes use of the same contract analogy you mention:

> Implementing an interface allows a class to become more formal about
> the behavior it promises to provide. Interfaces form a *contract* [emphasis added]
> between the class and the outside world, and this contract is enforced
> at build time by the compiler.

To implement an interface is to promise, to guarantee, that the class will come through on its end of the bargain and implement everything in the interface. The idea of a contract is already a successful analogy, so I wouldn't try to necessarily reinvent the wheel here lest you introduce more confusion with a different analogy. You could have students use the word promise if contractual language does not hit home for them.

Putting it in the context of friendship and promises being made might make them understand an interface in a better way than legal agreements and contracts. Ultimately, simple, relevant examples that clearly illustrate *why* interfaces are of value and how they are central to human-computer interaction will probably be of more value than a different, clever analogy.

You may find [this since-closed discussion on SO](https://stackoverflow.com/questions/3355408/explaining-interfaces-to-students) of value.

> **Comments:**
> **username_0**: The context of friendship sounds potentially useful.  
> **username_9**: I just want to add onto this remote example. I did an assignment for class where students were constructing interfaces/classes for a Samsung-esque company. So they had interfaces like `VoiceAssistant` that were then only implemented on some of their classes (e.g., smartphone, smart assistant, but not TVs). The students found it very effective!  

---

### Answer by username_6 on 2017-07-23. Score: 8

This answer draws on Java examples.

I start the interface discussion with a mechanical SATA hard drive in my hand. I discuss the interface called SATA and its universality across devices. I expand this with some digital images of SATA on an optical disc drive as well as a solid state hard drive. Some discussion follows regarding the variety of brands and companies but also the assurance of SATA's common functionality that makes it possible for everyone to play nice together and make reliable components that work across so many devices.

The students verbally list some functions of the SATA interface. I prompt them by asking what all these devices are required to do: read data, write data. Depending how long you want to spend on this and how it matches your curriculum, you get more information from them - what parameters might those functions have etc. Talk about data storage or bits and bytes if its relevant, etc.

All the while, I've listed these functions on the board. Finally, when I think we're done brainstorming, I wrap them in curly brackets and label it an interface. Be careful not to attempt an implementation of any of the functions. That doesn't belong in an interface. (Aside, digging into some Java interface source code, I was surprised to learn of the default function introduced in Java 8 - a lot of things surprised me really when I started digging into the Java source.)

This is my hook for the interface lesson. Next, I jump into all the textbook examples like Edible, Animal, or whatever other abstractions you're going to see at this point in a textbook.

Finally, whether the textbook likes it or not, I slap a Comparable vs Comparator (Java) problem on all of them and make them sort some Geometric objects or something. I spend the next 30 minutes walking around helping students comprehend compiler error messages like "Triangle and Rectangle don't implement the Comparable interface" or "Triangle must implement Comparable.compareTo" or something like that.

Inevitably, many questions about how compareTo works or should work come up. I explain -1, 0, 1 for <, ==, > respectively but then I will show them the source code for java.lang.String or wherever that is, and discuss how Comparable strings actually use the difference between ASCII character codes to compare characters. If not GeometricObjects, ask them how they would sort themselves - height? GPA? grade level? Obviously we need a Comparator for each property if multiple different sorts are needed. It may help to demonstrate that Collections.sort(arrayList) of complex objects won't work with Comparability.

When trying to nail the point, "Always program to an interface," my go-to example is the List interface. I say "Because it's easier to maintain later. If you change the interface, the compiler will require you fix all the implementing classes." I instantiate a few, Vector, LinkedList, ArrayList, with only the interface on the left hand side of the instantiation, List = ArrayList, for example. I show them the source code for the List interface in Java but with Oracle's comments removed so it's just a list of functions. I then show them the same set of common functionality across all implementing classes, only now it's listed in the Eclipse intellisense. This point about always program to an interface is apparently only worth mentioning because those who stay with programming will hear it again some day and you've laid almost a foundation. It's not a point I would spend too much time on with high school students. I drop the phrase and expect they'll hear it again if they carry on with software development.

... and right before I think they get it, time demands that we move on to something else. Hopefully some later assignments revisit the interface.

> **Comments:**
> **username_0**: Wow! This is a very good answer. Welcome to [cseducators.se], I hope we'll be hearing more from you.  

---

### Answer by username_4 on 2017-06-11. Score: 6

I believe that using the term "contract" is hurting more than helping. Most students in that age-range have no personal experience with contracts, so the term is too abstract or remote. Secondly, using contract to "define" the rules for using an interface is likely to lead to a circular definition when you define what a contract is. To increase comprehension for the students it is better to use something they already understand in explaining new concepts.

Using an analogy for how `implement` in the class declaration relates to the `interface` you could try using a survey form as an example. A fill-in-the-blank survey has no right or wrong answers, only questions that need an answer, but the answer has to be the right kind. A question about favorite color should not be answered with "scuba diving". If the form has five questions, and only four are answered, it is incomplete and thrown out as unusable, and no credit is given for doing it. In `interface` declaration is the same way. It lists the methods, their return types and their parameters, but they are blank methods that don't do anything. When the class declaration `implements` that interface it has to fill in all the blanks and how they are filled in has to match how the interface declared them, the same return type and the same number and type of parameters.

Once they have a grasp on the rules for using interfaces you can use interfaces to explain what a contract is, and how using an interface is part of fulfilling a contract.

> **Comments:**
> **username_0**: I like the analogy, but I'm not sure it'll make it clear that `implements` I'd binding  
> **username_4**: First day of the term, use a survey, with the stated rules that any open blanks on the survey is an error: no credit.  
> **username_0**: So then I could say that the student's answers implements `SurveyAnswer` and as such should contain answers for each question, and of the fitting type?  
> **username_5**: I don't even like the analogy. I believe this is no more of a contract than using strong types (or a rigorous formatting styles) which permits automated checking for consistency. My view (with zero experience of java) is that an interface definition permits the compiler to tell you when you've made incorrect assumptions. There is no mutually beneficial trade as implied by a true contract.  
> **username_0**: @SeanHoulihane that is not entirely true. There might not be any mutually beneficial trade, but it's not a definition that allows the compiler to know of incorrect assumptions, either. It is a binding construct. But the idea of a contract is useful. I am trying to explain that to the students.  
> **username_5**: @ItamarGreen, agreed in a formal CS context - but I don't work in that context, and I suspect few of your students understand the word 'contract' in the same way that either of us do. Accepted that Java has some supporting definition, but I dislike it.  
> **username_0**: @SeanHoulihane but this is about formal CS context, o.o... Regardless, You're right that only a few students understand the word contract in that way. That is why I asked this question.  

---

### Answer by username_7 on 2017-07-23. Score: 3

I have a bit of a quibble here. The only thing enforced by Java when implementing an interface is the *structure* of the class implementing it. The intent of the interface programmer isn't enforceable. Good names will help *express* the intent, but not enforce it. Good javadoc comments will convey more of the intent, but again it isn't enforceable. Absent some compiler/runtime enforcement mechanism of pre and post-conditions and invariants it is pretty unlikely that this will change.

Other languages do, of course, provide such a mechanism which leads to design by contract.

However, what we CAN teach our students is to program to the *intent* of the code we are working with and not just its structure. And that is always true, not just when implementing an interface. So, In my class the interface of the original post here wouldn't be acceptable, coming without clarifying javadoc comments. It is a contract (only) if you treat it as such. But lots of human interactions are similar.

BTW, students writing subclasses (which IMO is too often done poorly) break the intent of the superclass as well as the structure. Among other things, subclassing by adding public features makes Liskov's Substitution Principle impossible to obey. If you need to *cast*, your code is probably broken. I'll wait for a good question about subclassing in Java-like languages to talk about why that is.

> **Comments:**
> **username_0**: java enforces that an implementing class actually ***`implements`*** the method signatures defined in the interface. Anything that implements a specific interface is promising that you can work and use ***only*** the parts that are from the interface (`Interface objectName = new ImplementingClass()`). At compile time, you can use anything that `Interface` says, but not what `ImplementingClass()` can do which isn't related to the interface. My point is that I'm not sure I understand why you say that `intent` is the only thing enforced.  
> **username_7**: Declaring variables with the interface type is good style but, unfortunately only style, and that isn't enforced.  
> **username_8**: Domain Specific Languages have a lot of advantages and have existed since long before OOP came about. The biggest advantage, from my point of view, is that I can hand over a lot of 'programming' work to non-programmer domain experts, including ordinary folks. My first goal as a programmer is to make my services no longer required. I used to be quite successful at that.  

---

### Answer by username_9 on 2018-10-13. Score: 2

I really enjoy the answer to [this question](https://stackoverflow.com/a/14244705/290136) provided on StackOverflow and use it as a basic introduction/discussion point in my CS2 course:

> 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..."

> **Comments:**
> **username_0**: This is an incredibly simple and very nice answer. Thank you!  
> **username_9**: @username_0 It also is fun to see how much your students really have thought about the zombie apocalypse... :)  

---

### Answer by username_10 on 2017-06-11. Score: 2

An interface "isn't" a contract. But it *embodies* a contract. Implicitly if not explicitly.

A simple example is when you go to Kinko's (FedEx), and you click on the end of the opening interface that you agree with the terms of use. In turn, Kinko's agrees to provide you with a bunch of computer services, express or implied, for the money you are paying them.

Other interfaces don't necessarily have a paywall, but they usually have terms and conditions (going both ways), plus the requirement that you provide at least a minimum of ID to use them.

> **Comments:**
> **username_0**: [tag:interface] specifically isn't about the **user** interface, it's about the object oriented programming interface.  
> **username_5**: This analogy works. FedEx ask for payment, a box, and a destination. Whatever is in the box, they'll ship it even if you put perishables in the box (or lithium batteries), and their shipping method isn't appropriate. They don't guarantee the contents arrive unharmed, they just move the box and its contents. Mis-treat an API, and you have a validation problem.  
> **username_8**: @SeanHoulihane but I am hoping that FedEx would in fact enforce their conditions, because they don't want an entire truckload or plane cargohold of packages to burn up, whether I cared (or perhaps intended that) or not. Caring to protect yourself and your users is the bottom line.  
> **username_5**: @ScottRowe Your desires are irrelevant to the interface. There are implications for misusing the interface, but an interface which includes testing of its inputs is more expensive. Providing an un-validated interface may also be expensive (see GPZ vulnerabilities which use speculation and a cache side-channel) - this is reflected in your risk analysis.  

---

### Answer by username_11 on 2022-11-23. Score: 1

An interface is an artifact that exists between two or more abstractions. It states *what* capabilities a given abstraction has to offer its users. It does not say *how*. The *what* part is an interface, and the *how* part is the implementation. [A good interface is deep](https://blog.pragmaticengineer.com/a-philosophy-of-software-design-review/) (the implementation has much more volume than the interface). Its a characteristic that makes it similar to a physical contract.

How does it correspond to an interface? You sign a six-page-long contract - that corresponds to a proportionally small interface of your abstraction. Then you provide your service or a product - that corresponds to a proportionally deep implementation hiding a lot of domain, and contract-specific complexity. The contract not only enforces mutual obligations but also gives you (as a service provider) a lot of freedom in execution, as long as you don’t breach the terms, and meet the essential KPIs.

As real-life contract - an interface is a basis for collaboration. I've written more about the topic [here](https://medium.com/p/575553dcb6a2).


---

### Answer by username_2 on 2017-07-21. Score: 1

Java (and most other languages) interfaces are not contracts.
The contract on Eat is:

I take no data
I return no data
you can call me under any situation
I will not crash/throw (most languages don't even have this)
I will do what ever seem like a good idea to me

I.E. there is no contract. They don't see it because it is not there. Without pre and post conditions, there are no promises, there is no contract.
An example of a contract may look like this (I have to make up some syntax).
public interface Edible {

    public boolean isEdible();
    public boolean isEaten();
    public void eat() 
       precondition: isEdible();
       postcondition: isEaten();
    end

    invariant:
       isEaten() implies isEdible();
    end
}

> **Comments:**
> **username_0**: To quote [Oracle](https://docs.oracle.com/javase/tutorial/java/concepts/interface.html) on Interfaces: "Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler." So, it is a contract, in the sense of I'm talking about, which is what I'm asking about. Which is not exactly what you answered. Nevertheless, your comment on my example is useful.  
> **username_2**: I think oracle (or was it sun micro-systems), read that interfaces form a contract, and then noted that they had something that they called an interface, and then wrongly concluded that they were constructing contracts. This is an easy mistake if they did not know what the original author meant by interface. “an interface is defined in terms of the obligations of the sender and the receiver involved in an interaction. … Typically these are set forth in preconditions and postconditions … invariant conditions.” — B.Meyers (1994)  
> **username_0**: that may be. But do you agree that *it* ***can*** *be thought of* as a contract?  
> **username_2**: @username_0 If a Java interface is a contract, then. What do the two sides in the contract promise? I have around 25 years programming experience, and I can not see it. I would not expect my pupils to see it. Can you explain how Java interfaces are contracts to me.  
> **username_7**: @richard, perhaps "intended contract" is a better term. It certainly can't be enforced in Java. But the software is generally better if everyone agrees to behave as if it were.  
> **username_2**: @username_7 but where is the behaviour agreed? I can see that you can use good-names, and you could but the contracts into comments. I could agree that this is an implicit contract, if the names are good, e.g. draw_line(start: point, end: point), we would expect this to draw a line, between two points.  
> **username_0**: @richard and anything implementing that interface **must** implement `draw_line` method (which means write a method body). Btw, I'm sorry for the confusion. I mistagged the question. Now I see that tagging with [tag:java] is needed.  

---

### Answer by username_12 on 2022-12-28. Score: 1

If I were asked to describe how a pin-and-tumbler lock works - the kind of lock most of the developed world have on their front doors - I cannot imagine that the word "contract" would find its way into the explanation.

This is despite the fact that, if you squint really hard, the relationship between the key (on the one hand) and the keyway and pins (on the other hand) does involve some kind of match, and the existence of the lock and key does in some sense govern the relationship between householder and strangers.

There's probably already a number of people who have no ready idea how pin-and-tumbler locks work to understand this analogy, and many more who would wonder where on Earth I pulled this from.

Likewise, many middle-age adults (let alone high school students) would have no clear idea what a "contract" even is, beyond some kind of lengthy document written in small print, that some corporation imposes on you as part of ordinary and necessary daily dealings *in order to evade their legal liabilities*.

Even if you ask a lawyer, they'd say a contract involves offer and acceptance, consideration on both sides, an intention to enter legal relations, and so on.

Does any of this seem to have the remotest connection to defining an "interface" in an OO programming language? I would say not.

I think that OO programming is actually very complicated to explain, both in computer science terms, and in terms of a certain philosophy or ideology that is associated with "pure" OO programming.

To add to the hassle, mainstream programming languages are a muddied synthesis of both OO concepts and non-OO concepts (with the non-OO concepts being something that don't reconcile with the OO concepts), and the most compelling demonstrations of the capabilities of OO programming involve software development being done at quite some scale with a division of labour (which is at odds with how most young programmers practice coding, which is as a solitary activity, and at odds with their industrial experience, which is zero).

Quite frankly, I would not even try to teach interfaces to high school students in terms of abstract concepts - unless you're dealing with a classroom of savants.

I would either just declare the concept to be something that is advanced beyond the level of your course, or I would demonstrate some practical examples of how interfaces can be used, without trying to explain their conceptual nature in a generalised fashion.


---

### Answer by username_13 on 2023-01-03. Score: 0

Rather than thinking of motivating examples, I prefer to teach it from the perspective of polymorphism. The mechanism of polymorphism **requires** an object referenced by a reference of the interface type to have a valid implementation of the method (and implementing the interface allows the compiler to enforce that requirement). So rather than teaching it as being merely a contract, I teach it as being part of a key mechanism in the Java programming language. I think it is important that students learn the underlying logic of a programming language and I think it is better to teach the principles rather than just presenting lots of examples and hoping the students will infer the mechanism for themselves (some will, some won't). Of course you need examples as well, to show the cool stuff you can do with the mechanism.

Of course this isn't the only use for interfaces, but it explains *why* the interface enforces a contract of sorts. Those other uses can be explained later, and when you do, the students will already understand that implementing an interface enforces a contract, so they can focus on the new use, rather than the mechanism.


---

