Interface in Java with programming Examples

Interface in Java

In Java, there are not only classes but also interfaces. These are introduced with the keyword interface instead of the keyword class. Interface in java, like classes, should each be stored in a separate Java file. In terms of structure, interfaces are very similar to a class; they are almost comparable to abstract classes that only contain method declarations. The only difference to a class is that an interface in java has no implementations, just method headers, and constants.

Let’s take a look at the syntax of an interface in java

The header of an interface in java is structured like that of a class, except that the keyword class is replaced by the interface in java. Only constants and method names can be in the body of the interface.

Among other things, interfaces are used to separate the specification of classes from their implementation. But you can also use interfaces to protect the actual implementation from third parties. Interfaces and the methods they contain can therefore also be used as communication interfaces since the transfer parameters to be expected and the return value is defined by the method header.

Like classes, an interface in java can also have an inheritance hierarchy. The same rules apply there as for classes (single inheritance, visibility, etc.).

But since we also want to use interface in java, we have to integrate them into a class somehow. This is done using the implements keyword. The following example shows how the MyInterface interface above is included in a class.

We can easily extend the normal structure of a class with the new interface by including our interface MyInterface in front of the class body with the keyword implements. Integrating an interface can take place parallel to inheritance. You can include any number of interfaces in a class, the interface names are then simply separated by a comma in the class header. This is often used to simulate a kind of multiple inheritances in Java since this is otherwise not directly possible.

Let’s look directly at a concrete example.

Example: how to use Interface in java

In the example above, we have created an interface called PrintMessage which will be included in the Test class. The Test class must then implement the method declarations from the interface.


interface in java

Java multiple interfaces in a class

Since we can only simulate indirect multiple inheritances in Java by including multiple interfaces, we now want to deal with this topic in more detail.

Integrating multiple interfaces in java is not always possible. For example, the same method may be declared in two interfaces and the method declarations differ only in the return value. In this case, it is not possible to integrate these two interfaces at the same time. If the two method declarations are the same, both interfaces can be integrated, but the method then only exists once in the class.

Constants from different interfaces can have the same name but a different value. However, this should be avoided. However, you can then access the respective constant by specifying the interface name.

Let’s take a look at an example.

Example: how to use multiple interfaces in a class in java:

In the above example, we have two interfaces Section1 and Section2. Both have two constants and a method. This is followed by the start class Test, which integrates our two interfaces Section1 and Section2. The method from the interfaces Section1 and Section2 is not critical because it is declared the same in both classes. In addition, the interfaces each have a constant with the same name, VAR1, but a different value, and a completely different constant, VAR2 and VAR3.
Our start class Test now implements both interfaces. The Test class also has its own constant called VAR1. In total, there are three times the constant VAR1, each with a different value. The setValue method is implemented in the Test class, ie we give it a method body at this point.

In the main method, we now output the constants.


interface in java

Special interface in java

In Java, there are already some predefined interfaces that can be integrated for specific tasks. In the following, we want to look at some more special interfaces. Interfaces are often used to deal with or react to special events. A large part of interfaces is used in the area of ​​GUI (Graphical User Interface) development. Graphic surfaces have to react to inputs, for example, there are special interfaces for this. We will go into more detail about these special interfaces later in the articles on GUI programming (event handling).

Cloneable Interface in java

A special interface in java is the Cloneable interface. This serves to create an exact copy of an object. Normally one would think that an assignment also creates an exact copy of an object. However, this is only the case for simple data types. In the case of objects, however, when an assignment is made, there is only a reference to the memory area in which the object is located. To illustrate this referencing, let’s take a look at the following example.

Example1: how to use Cloneable interface in java:


interface in java

Program Explanation:

In the main method, we first create an object of the copy class and assign it to the variable ref1. Right after that, we assign the value of ref1 to the variable ref2. If we now look at the output, we see that the first two outputs are identical. This is also not surprising since the first two outputs occurred directly after the assignment (ref2=ref1). The other two editions are more surprising. We recently changed the x attribute of ref1. Therefore, one might have expected that the output from both objects ref1 and ref2 are different. But since we already said before this example that an assignment to objects does not create a copy of the first object, but only refers to it, this output is only logical, since we are referencing the same object via both variables.

Please see the following pictures for illustration.

interface in java

In the above image, you can see the assignment from our object ref1 to ref2. Both “point” to the same object. This type of assignment also happens with method calls that have objects as transfer parameters. This allows you to implement multiple return values ​​in a method by changing the attributes of the object. However, this is not always desired and therefore one must first consider whether one actually wants to change the existing object.

interface in java

if we really want to copy the object, we have to clone it. The cloning is shown in the above image. Here each variable points to its own object after the cloning process. At this point, a change does not affect the other variable.

We now extend our copy class and implement the Cloneable interface there.

Example2: how to implement the Cloneable interface in java:


interface in java

Program explanation:

We have now included the Cloneable interface in our Copy class. For this reason, we also implement the clone method. At this point in the clone method, we simply call the clone method of the superclass, namely Object. Then the cloned object is returned or the exception CloneNotSupportedException is thrown. Now if we look at the output, we see that our cloned object has not changed after we made the change to the object referenced by ref1. Since the clone method can throw an exception, we also need to add error handling and catch that exception.

Experienced developers can see from the source code that the error handling has not been solved well. Two other exceptions that could not have been caught or detected by simple inspection may occur. The first additional exception that should have been caught in another catch block would be the TypeCastException that can occur during type conversion from Object to Copy. The second additional exception that can occur would be the NullPointerException. If an exception occurs in the try block, ref2 remains at the value null. With the method call ref2.print() the NullPointerExceptionthrown.

You can also implement the clone method yourself by creating a new object of the class to be copied with the new operator and assigning the existing attributes, provided they are simply data types, to the new object and then returning the newly created object. Depending on which superclasses exist, you may have to implement the method yourself and not call super.clone(). Let’s now look at a separate method clone for the above class Copy, without including the superclass.

This is a very simple example, but basically calling the super.clone() method does nothing else. With more complex objects, of course, more attributes have to be “cloned”, so the method would contain a few more statements.

Java interface as a data type:

Interface in java can also be used as a data type. It should be noted, however, that no object can be created from an interface using the new operator. An instance of an interface can only be created via assignments, by assigning an object of a class that implements the interface to a reference variable that has the interface to the data type.

This also makes it possible, as shown in the following example, to store objects of different classes in an array.

Let’s look at a small example first.

Example: how to use java interface as a data type: 


interface in java

Program Explanation:

At this point, I used anyName1 and anyName2 classes and the myInterface interface.  The anyName2  also integrates the myInterface interface, and also implements its methods. This class also has an attribute y and the associated get or set method.

In order for us to test this, we need a starting class Test. There we declare two variables Object1 and Object2, which have the myInterface data type interface, and assign an object of the anyName1 type to the first and an instance of the anyName2 class to the second. We then declare an array whose elements should be of the myInterface type. We then call the setX method from the interface for each object. Then we move the Objects into the array and let us output the x-values in the for loop via the method getX declared in the interface.

You can see that the anName2 class has one more attribute and two more methods. However, these are no longer accessible after the assignment to the variable Object2, since the object only has the methods of the interface. It would first have to be typecast to the anyName2 class for access to be possible.

As you can see from this example, interface in java can also be used as data types, but it should be noted that only the methods declared in the interface can be accessed. Access to the methods additionally implemented in the original class is not possible.

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: