I believe that the one who else introduced the idea of a user interface might not have thought how fantastic the sensation was in its features. Although this is just my guesswork. In any kind of case, the concept associated with the interface has extended the options of OOP very strongly.
So what is the interface? Essentially, this particular is a description of bare functionality without any kind of bindings towards the class functions. If to convey figuratively, the classes possess the opportunity to possess a profession – the sender of the mail, transaction manager, page distributor, controller, etc. I am right now trying to bring straight down the grandeur of this particular idea, and I realize that it is not however possible. Simply take a term – it’s great. Along with the help of interfaces, relations between objects turn out to be more flexible, which enables building the architecture of applications within much more independent blocks.
Again, if we return to the example with the profession, then, actually, you may not care about gender, eye colour, age group and height of the individual who works as the driver, electrician or developer. It is important to you that they know exactly how to do this function and how to do it well (to some extent). Also, it is important that both a person and a class may have several professions (apply several interfaces). If return to the inheritance topic, then, it is nicely known, a class could be inherited ONLY FROM A SINGLE class. However, it can have quite a lot of interfaces.
Let’s move from words to deeds – back to our class Robot.
Last time we taught it to move and memorize its route for display on the form. When creating it, we ran a little forward – I introduced the class, which we will certainly not discuss for a few time – ArrayList. Till we discuss it – I’ll just note once again that this class allows you to work with dynamic lists of objects – add, delete, view, iterate. Let’s expand the capabilities of our robot – we will give it the ability to tell someone that it started to move forward and stopped. It is possibly not such a useless thing – for example when observing the rover.
Let’s focus our attention on the words “inform someone”. This is a very delicate moment – the robot, after all, doesn’t really matter to whom to report. Here it is, the point of application of the interface – it doesn’t matter to us who will listen – it is important for us that someone or something is able to listen to our message, to comply with a specific contract. It’s time to see how the interface is defined.
As you can see, the interface description is a fairly simple process – it is much more difficult to understand when it is really needed. Now, let’s consider it in some detail.
First, to describe the interface, you need to use the word interface. Secondly, the methods do not contain the body – at all. It is simply against the rules. Only the description is created — accessibility, return type, and input parameters. After that, we put a semicolon.
You may have a question – why do we pass x and y coordinates to interface methods? Quite a reasonable question, but here is also quite a reasonable answer – the robot must also report where it started and where it stopped.
It is time to modify the robot’s code so that, firstly, it can register the “listener”, and secondly, it must be able to work with it. Let’s take a look at the code.
There are three moments in our code that we should pay attention to. The first one is declaring the link to a listener.
private RobotListener listener;
Yes, it is the same solution for objects’ relation. No magic here again – we need to tell our robot whom to sell the messages/ The second thing is that we will need a method for setting a listener:
Finally, the third thing – in method forward the robot calls the listener. Take a look – we check for NULL before the call. The matter is that if the listener is not set, then we can get a not funny NullPointer error – the pointer is empty. Such mistakes are made by pretty experienced developers as well, so you need to be attentive. It is a pretty insidious error, albeit simple in debugging.
This way, our robot is ready to send events and now our task is to create the same listener. ATTENTION PLEASE – you cannot create an object of interface type. It is pretty similar to an abstract class, but the abstract class contain at least some code, but the interface does not contain any. In case we return back to the profession analogy, then the existence of a doctor at the hospital means the existence of an individual who obtains a doctor’s profession. It is all the same with interfaces – we need to create a class, that implements a required interface. Yet again, a class can implement more than a single interface. Let’s now create a simple listener:
As you can see, the notation is simple enough – if you want to say that the class implements the interface, you write the word implements and then specify the necessary interface. If you need to implement multiple interfaces, they are written with a comma – for example:
If you create a class that implements an interface, you must have methods in this class with exactly the same descriptions as in the interface. Those. Now our class will produce an error when compiled. Let’s make a simple transaction.
I hope you remember what the @Override annotation means — we have already discussed this. In order not to run on the links – this is a special designation that the method is redefined.
The listener is ready – it remains only to connect it to our robot and run the program. The connection is made through a call to the setListener method. We can do this in the RobotManager class.
In code, we create a SimpleRobotListener object instance which implements RobotListener interface and class Robot effortlessly allows to set a listener for it. We need to emphasize an important thing – it does not matter for class Robot what class implements the required interface. Speaking more accurately, while creating SimpleRobotListener it is recommended to write the following:
We can also recall polymorphism – the class knows how to be a robot listener (he has such a profession). And we work with an instance of the class SimpleRobotListener as with the profession RobotListener. Such abstraction is very convenient when designing – you will see it. You are not tied to specific classes – you are tied exclusively to the “profession”.
Now, when launching our program, the text that our listener should output will be visible in the output console.
Properties and constants
Due to the fact that an interface is only a description of what to do, it does not contain info about how to do (as you have already seen, the methods do not contain implementation), thus an interface cannot include properties as there is no place to call them. Here is an only exception – an interface can contain constants, something like this:
We can address field NAME as a constant. I think that everything here is pretty obvious and easy-to-understand – you can describe constants in an interface that can be in-demand.
Let’s consider an example that allows us to generate an online graphical application in which we will use interfaces. I am very warm to the examples that allow you to aesthetically see the work program. And graphics applications are extremely appreciative material. Therefore, our task is to create an application that will use the control keys to go a square around the screen.
There will be two buttons on the form – UPWARD and DOWN, which allow you to move the square up and down, respectively. The application itself is not difficult – it is very important see the use of interfaces.
Buttons are actually very similar in their idea to our robot – when clicked on in it, they are able to send events to those objects that they have registered as listeners. Moreover, the buttons are allowed to have many listeners at the same time – a whole list.
We give the code of the form that contains three components – 2 buttons for control along with a panel that can attract a square with particular coordinates and, which will be important to note correct away, can “listen” in order to events from the control keys. The opportunity to listen is accomplished very simply – our own panel implements the ActionListener interface (this interface will be described in the Golfing swing library). Moreover, the particular element can pay attention to events from both buttons — it is registered as a listener for both. Therefore, look at the program code:
If we read this code accurately, we can see that initially, we create a panel, then – buttons. While creating buttons, we name the panel (right in the constructor), then we set it the command’s name (in order to allow the panel to differentiate the event it was called by – button UP or DOWN). Calling the method addActionListener, we register our panel as an event listener. Finally, we set our button to either UP or DOWN. We have already discussed the layout topic in polymorphism chapter, so by default, the form uses BorderLayout – here the components are placed by the world’s sides: north, south, east, west, and centre. If you do not specify the direction, then the component will be placed in the centre.
Let’s now take a look at our panel’s button code – it should not become too difficult for you, as we have used the method of rendering many times.
A new thing for you will be actionPerformed method. This method is described in ActionListener interface.
Новинкой для нас будет метод actionPerformed. Это метод, который описан в интерфейсе ActionListener. And the button is completely indifferent to which class it is listening to – it may be another component, a class for recording files, for sending mail, and a sea of all other classes. Just a contract is important – “I can listen to the button.” This allows at times to increase the flexibility in the design. Returning to the method – it takes as a parameter a special class / object that contains interesting information about the source of the event – in this case about the button. In our case, we are very interested in the parameter that we set – getActionCommand / setActionCommand. He will tell us which button is pressed. Once again pay attention to the pleasant opportunity to listen to events from both buttons.
And finally, the code to run our form:
I suggest you expand the example – add the LEFT and RIGHT buttons there and move the square to the sides. You can also make sure that the square “does not run away” off the screen.
Interfaces play a very important role in a large number of technologies, design patterns. We considered only the main ideas and forms of writing.