Home java OOP Interfaces (Java), Simple?

OOP Interfaces (Java), Simple?




Answer 1, authority 100%

General definition:
An interface is a set of methods and rules for the interaction of system elements. In other words, the interface defines how elements will interact with each other.

  • Door interface – handle presence;
  • Vehicle interface – presence of steering wheel, pedals, gear lever;
  • Rotary Phone Interface – Handset + Rotary Dial.

When you use these “objects”, you are confident that you can use them in this way. Because you are familiar with their interface.

Something similar in programming. Why is the graphical part of the program often called the interface? Because it determines how you can use the main functionality of the program.

“The interface determines how we can use the object” – let’s transfer this thought into the programming plane.

Suppose you have the following types in your program:

// some basic interfaces, they are empty,
// since their content is not essential at the moment
interface Rul {}
interface Pedal {}
interface Kpp {}
// the interface describes the interaction with the car - i.e. its interface
// gives other objects access to the wheel and pedals
// (in fact, this interface corresponds to a car with an automatic transmission)
interface Car {
 Rul getRul ();
 Pedal [] getPedali ();
// this interface extends the base
// and also provides access to the gearbox
interface CarWithKPP extends Car {
  Kpp getKpp ();
// and here we have the car itself
// method implementations are omitted because not essential
class SomeCar implements CarWithKpp {...}

and now let’s see how you can use what we have:

// create a new object
SomeCar instance = new SomeCar ();
// do some actions on the object
testAction1 (instance);
testAction2 (instance);

As you can see, we use them in the same way, but the point is in the implementation of the methods:

void testAction1 (CarWithKpp c) {
  c.getRul (); // can
  c.getPedali (); // can
  c.getKpp (); // can
void testAction2 (Car c) {
  c.getRul (); // can
  c.getPedali (); // can
  c.getKpp (); // not allowed, compilation error. this method is not defined in interface Car

On the one hand, the fact that SomeCar inherits the CarWithKpp interface (and through the latter also Car ) allows us to use it for working with the testAction1, testAction2 methods. The interfaces that are implemented (implemented) in the SomeCar class provide access to its correct use. Also, using an interface in a method signature ensures that you get exactly the type you want.

The downside of the coin is that the interface imposes restrictions on the use of the class. An example of this is that in the testAction2 method, it is no longer possible to access the getKpp method. Thus, you can hide the methods and properties that are declared in the CarWithKpp interface, as well as the methods declared in the SomeCar class (if they are not in the interface). Both methods can only use the set of “tools” available to them (this is defined by the interface).

Answer 2, authority 17%



It may seem strange to you, but this is exactly what distinguishes humans from animals – the use of interfaces instead of classes. You probably remember the classic experience with a monkey, who was taught to extinguish a fire with water from a bucket; and then they put the bucket on the raft in the middle of the pool, but the monkey still ran across the bridge onto the raft and drew water from the bucket, instead of scooping water directly from the pool. That is, the monkey used the Water-in-Bucket class instead of the Water interface (and even more, I’ll tell you a secret: instead of the Extinguisher interface).

When we think in classes, we are like animals. People think (and program) in interfaces.

Answer 3, authority 15%

Speak simple? Well, ok, the truth is now all sorts of comrades like gurus will start spitting here 🙂

An interface is the ability to look at a class as an object of a slightly different type.

Let me explain: well, as if the name speaks for this. An object in OOP is a certain entity that has its own set of methods and work with it – we will call the methods conditionally “gates”, and the interface is a “door” in these “gates” – a slightly different way of handling the same object. So if you forget about the “gate”, it seems like a different object. The key word here seems to be.

Example: there is a table object that has methods of working with it: like eating while sitting at it, covering a havchik on it, placing, assembling, sawing off legs, etc. But the same table object can be viewed as an interface furniture (in OOP language, this is called a class of table type that implements an interface of furniture type: class Table implements Furniture . It is clear that not all furniture can be eaten or a leg can be sawed off, but what is certain is that the furniture can be delivered and assembled.

Now what is all this for. Again, an example with furniture – if, say, there is a chair object that also implements the furniture interface, then both the chair and the table can be treated in the same way – this is the meaning of the interface – to unify work with different types of objects .

Answer 4, authority 14%

Answer 5, authority 7%

An interface is a description of what an object of a class that implements this interface can and should be able to do.

Let’s not be original and take the door as an example.

What can an ordinary person do with a door? Open and close.

Accordingly, the interface for it will be as follows:

interface Door {
  public boolean isClosed ();
  public boolean open ();
  public boolean close ();

Now watch your hands. The human object needs to go through the door. It is important to him what kind of door is the door in front of him, wooden, iron, with a window, does it open towards itself or from itself, or maybe even moves to the side? No, it doesn’t matter. It is important for him that in principle it can be opened.

Therefore, in the “Person” class, we do not accept a specific door into the “Pass through the door” method, but in principle the “Door”, because we know that it has the “Open” method.

class Human {
  public void goThruDoor (Door door) {
    if (door.isClosed ()) {
      if (! door.open ()) {
        throw new Exception ("the door won't open :(");
    goForward ();
    door.close ();

Accordingly, the following is an example of two objects that implement the “Door” interface and which can be passed to the “Person” in the “Pass through the door” method, but implement different logic for the “Open” method.

class WoodenDoor implements Door {
  private boolean closed = false;
  public boolean isClosed () {
    return closed;
  public boolean open () {
    if (! closed) return false;
    closed = false;
    return true;
  public boolean close () {
    if (closed) return false;
    closed = true;
    return true;
class LockedDoor implements Door {
  private boolean locked = true;
  private boolean closed = false;
  public boolean isClosed () {
    return closed;
  public boolean open () {
    if (locked ||! close) return false;
    closed = false;
    return true;
  public boolean close () {
    if (closed) return false;
    closed = true;
    return true;

Answer 6, authority 5%

The interface ** of the object is the set
operations (methods) that he can
commit or which can be committed
over it. For example, the interface of the number 3
is called, in fact, “Number” and
includes a set of operations
addition, subtraction, multiplication and
division. Implement this interface
can any number of types / classes,
for example, the types Integer,
RealNumber, ComplexNumber, and
also non-obvious types such as
Interval or Polynomial. In the same time,
the same type can implement
more than one interface. So,
Integer Number other than interface Number
can implement interface
Enumerable – for this in the class
Whole number will be needed only
redefine the next operation and

Answer 7, authority 3%

I will explain without details.

Let’s say we created a Framework that determines if the user double-click across the screen.

There we defined a function: what_to_do_if_user_clicked_2_ times_on_screen () .

But we decide not to define the behavior of this function ourselves, but to provide this implementation to the programmer using our framework. The provision of this implementation can be done through the interface mechanism.

Function: what_to_do_if_user_clicked_2_ times_on_screen () stick it into the interface.

And thus, the very moment of double-clicking on the screen determines our framework, but what to do (draw stars on the screen, start playing music, etc.) after this event is decided by the programmer who implements our interface.

Benefit: the programmer does not need to think about how to catch double-click . Behind it is only the implementation of the response to this event.

Answer 8, authority 3%

Imagine a group of friends. They are all people and have their own characteristics, professions (someone is a miner, someone is a bartender, etc.). Then the lads came to the bar to sit and drink a beer. And the bar is like this – if you want to be clients of the bar – no question, implement our “Client” interface, and here’s a set of actions that you must implement as a client: Buy a beer, sit down at a table, drink a beer, pay the bill. All friends are different, someone is a doctor, someone is a plumber, someone without an arm, someone with a tattoo on their forehead (I know a strange bunch)), but when they come to the bar, they are all “clients” and must implement the interface “Client” with its methods. Yes, each of them implements the interface in its own way – someone will tip when he pays the bill, someone will break the bottle on his forehead when he is drinking beer, well, etc. (this is already polymorphism), but all of them customers at the moment and the bar staff interact with them as customers, not Vasya (miner), Petya (alcoholic). etc.
In general, interfaces are needed to associate a group of unrelated objects that must implement the behavior of that interface so that you can interact with them through this common interface.

Answer 9, authority 2%

“why and what for”:

1) Interaction with the outside world. Programs are written by more than one person, they do not consist of one class and often not of one package and module. And the essence of the program is that the code of different authors, different modules interacts with each other. The simplest example: you are using third-party libraries. You have found the class you need, connected the library that contains it and call methods from there. At some point, the author of the library decided to change his code, is that rare? Fix identified bugs, improve, expand functionality. And this may come as a deep surprise to you: your code is tied to its code! And your code suddenly breaks.

To prevent this from happening, so that someone else’s open source could be used by third-party developers without surprises, we came up with interfaces. An interface is a functional declaration. The implementation of an interface by a class is a guarantee of the implementation of the functionality. If a class implements an interface, then it promises that it has methods declared in the interface, they take the declared parameters and return the declared value.
You may wonder: but interfaces are also code and, like a class, can be changed. Can. But in practice this happens very rarely, the interface is a declared contract and we understand that our interface, if it is open, can be used not only by us.

2) In Java, an interface can act as a reference to a variable. For example, the following method is appropriate:

public void letsIterateABit (Iterable something) {// Iterable is an interface that has an iterator () method.
  // some code
  something.iterator ();
  // some more code

Any object that implements the Iterable interface can be passed to this method. Of course, in this case, we will be able to call only those methods that are in the interface. But sometimes that’s more than enough!

3) Interfaces allow you to implement dependency inversion . If you figured out the first two points, but did not figure it out – you are doing well, come back to reread the article in six months.

Answer 10, authority 2%

If you are familiar with circuitry, electronics, then the interface is like a multiplexer – one output and many inputs.

Or another analogy. Revolver with a drum. In the drum, cartridges (implementation) are fed into the bore (interface).

In general, this is a way of passing classes over a unified channel (on behalf of an interface – polymorphism) to another class. In this way, multiple inheritance can be ensured. The interface allows you to define a standard for object interaction during design. At the same time, changing (improving) the implementation of interfaces, you do not touch the standard itself. It’s comfortable. We can say that this is an abstraction of the description from the implementation.

Answer 11

Interfaces are the basis for the interaction of all modern information systems. If the interface of an object (personal computer, program, function) does not change (stable, standardized), this makes it possible to modify the object itself without rebuilding the principles of its interaction with other objects (for example, learning to work with one program under Windows, the user can easily master others – because they have the same type of interface elements).

Answer 12

In a simple way. The problem with multiple inheritance in many programming languages ​​is solved simply – either allow or deny. The Javists decided to sit on both chairs and chose their own, special path. Java, in principle, is not good at multiple inheritance of classes. If we write the keyword extends , then we know that we will only inherit one class, be it abstract or regular. But in order to simplify design and ensure compatibility, you also want to have buns from multiple inheritance, and this is where interfaces appear on the scene. An interface is a list of methods (only public (you don’t even need to write this word, there can be no others in the interface), and only WITHOUT implementation) and variables that are required, well, anyway there is in the class- descendant. And here you can push as many interfaces as you like through the implements keyword. And you can inherit them from each other. Thus, an interface is a guarantee that the classes that implement it contain the methods and variables that are listed in it. Because the expression ourObject instanseof ourInterface returns true, we know for sure that ourObject has methods listed in ourInterface

Answer 13

I liked the CodeGym definition:
In a broader sense, the interface of a thing is a mechanism for the interaction of this thing with other objects. For example, a TV remote is a remote interface. The dog understands and obeys commands – this means that the dog supports the voice interface (control). To summarize all this, then we can say that an interface is a standardized way of interaction between two things, and this standard is known to two parties. When a person tells the dog to “sit”, he gives the command according to the “dog voice control interface”, and if the dog executes this command, then we say that the dog supports this interface.

It’s the same in programming. Methods are actions on an object, on its data. And if a class implements certain methods, then it “supports execution” of certain commands.

Answer 14

Interface is the promise of implementing methods in a structured way.

Methods promised in the interface must be implemented in classes.

Examples of interfaces:

  1. Smartphone interface, in it we say that the smartphone object will have a weight method.
public interface Smartphone {
  public int weight ();
  1. For the NFC module, we have created a separate interface so as not to promise to implement this method in every smartphone. We follow the words.
public interface NfcModule {
  public boolean use ();

Class Implementation

public class SmartfoneMotorolla implements Smartphone, NfcModule {
  public int weight () {
    // 200 grams of smartphone weight
    return 200;
  public boolean use () {
    return true;

Answer 15

Interfaces are designed to support dynamic call resolution
methods at runtime. Typically for normal execution
calling a method from one class in another, both classes must be present at the time
compilation so that the Java compiler can check for signature compatibility
methods. By itself, this requirement creates a static and non-extensible environment.
distribution of classes. In such a system, functionality is inevitable
are passed up the class hierarchy, with the result that the mechanisms will be
becoming available to more and more subclasses. The interfaces are designed
to prevent this problem. They isolate the method definition
or a set of methods from an inheritance hierarchy. And since the interface hierarchy
does not coincide with the class hierarchy, then classes that are not related in any way between
themselves hierarchically, can implement the same interface. It is in this
the capabilities of the interfaces are manifested most fully.

Page 245, Chapter 9 “Packages and Interfaces”, Java 8 The Complete Guide. Schildt. 2015

Answer 16

Set & lt; String & gt; set = new HashSet & lt; String & gt; ();
set = new LinkedHashSet & lt; String & gt; ();
set = new TreeSet & lt; String & gt; ();
HashSet & lt; String & gt; newSet = new TreeSet & lt; String & gt; (); // - impossible

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions