Java Interface with Programming Examples

Java Interface Description:

Java interface with Programming Examples:- In this article, I am going to show you the uses of the interface in java programming with full explanation and programming examples.

Basic Syntax of java interface:

Java Interface concept:

An interface in Java is not a class and represents a number of requirements, presented to the class that must match the java interface. Usually, one developer looking to take advantage of another developer’s work to solve a specific problem, declares: “If your class will match the specific java interface, I can solve my problem. The sort() method from the Array class allows you to sort an array of objects when one condition: objects must belong to classes that implement the interface Comparable.

This java interface is defined as follows:

This means that any class that implements the Comparable interface must contain the compareTo() method that takes a parameter of type Object and returns an integer value.

All java interface methods are automatically considered public, therefore, declaring the method in the java interface, it is optional to specify the access modifier public. Of course, there is also an implicit requirement: the compareTo() method should actually be able to compare two objects and return a sign. In such a case, this method must return a negative numeric value if object x is less than object y, null if they are equal, otherwise, a positive numeric value.

This particular Java interface has a single method, and in some java interfaces, there may be more than one method. As will become clear in the future, with the help of java interfaces, you can also declare constants. But this is not more important, but the fact that java interfaces cannot be provided. In particular, they lack instance fields. Before Java 8, it was not possible to implement methods in java interfaces, but now they can provide simple methods. Of course, these methods cannot refer to instance fields as they are simply missing in java interfaces.

Now let’s say that you want to use the sort() method from the Array class. to sort objects of type Employee. In this case, the Employee class should implement a Comparable interface.

In order for the class to implement the java interface, you need to do the following actions.

  • Declare that the class implements the interface.
  • Define in the class all methods specified in the interface.

To declare the implementation of the interface itself in the class, use the keyword implements:

class Employee implements Comparable

Of course, now you need to implement the compareTo() method, for example, for comparison employee salaries. Below is the code that implements the compareTo() method in the Employee class.

This code calls the static Double method. compare() returning negative numeric value if the first argument is less than the second; zero value if the arguments are equal; otherwise, a positive numeric value.

Note: When declaring the compareTo() method in the java interface, the access modifier is not specified because all java interface methods are automatically public. But java interface implementations, this accessibility modifier must be specified indefinitely. On the contrary In this case, the compiler will assume that the scope of this method is limited to n package, although by default it does not go outside the class. As a result, the compiler will issue a warning the attempt to provide more limited access rights.

You can make a more elegant solution by implementing a generic interface Comparable and supplying with a type parameter as shown below. As you can see now the type Object does not have to be cast to the required type.

Note: The documentation for the Comparable interface assumes that the method compareTo() must be compatible with the equals() method. This means that the result of the comparison x. compareTo(y) must be equal to zero if the comparison results in the same result x.equals(y).

This rule is followed by most of the classes from the application software the Java API, which implements the Comparable interface. The most notable exception the BigDecimal class is used from this rule. So if x = new BigDecimal(“1.0”)

and y = new BigDecimal (“1. 00”) then the result of the comparisons. equals (y) boolean is returned false because the numbers being compared have different precisions. But at the same time as a result of comparisons. compareTo(y) returns null. Ideally, it should not be. But it was obviously impossible to decide which of these comparisons was more important.

It should now be clear to you that to sort objects, you just need to implement in the class, the compareTo() method. And this approach is quite justified. After all, I must there is some way to use the sort() method to compare objects. But why not just provide a compareTo() method in the Employee class, without implementing the Comparable interface?

The fact of the matter is that Java is a strongly typed programming language. When calling of any method, the compiler must make sure that this method really exists. The sort() method body can contain operators similar to as follows:

The compiler must know that the object a[i] actually has a method compareTo(). If variable a contains an array of objects that implement the java interface Comparable, then the existence of such a method is guaranteed, since each class that implements a given interface, by definition, must provide the compareTo() method.

Example: This program demonstrates the use of Comparable interface in java: class code: class code:


java interface

Java Interface properties:

Interfaces are not classes. In particular, the new operation cannot create an instance of the interface as follows:

But, despite the fact that it is impossible to construct interface objects, declare java interface variables can be as follows:

In this case, the java interface variable must refer to an object of the class that implements the given interface as in the below code snippet.

As you know, during the instanceof operation, it is checked whether the object belongs the given class. But with this operation, you can also check if implements whether the object is the given interface:

Like classes, java interfaces can also form an inheritance hierarchy. This allows you to chaining interfaces away from more abstract to more specialized ones. Let’s say you have the following interface Moveable:

In this case, you can create a Powered interface that extends the interface Moveable as follows:

Although an interface cannot have instance fields or static methods, you can declare constants in it:

Like methods, constant fields in java interfaces are automatically made public. And besides, they are static and final (i.e. they have by default access modifiers public static final).

NOTE: If you specify the keyword public n when declaring a method in an interface, and n fields designate as public static final, it will not be an error. Some programmers do not this is not a habit or to make the source code of their programs more readable. But in the Java specification, it is not recommended to use unnecessary keywords, and here we follow these recommendations.

Some java interfaces only declare constants and not a single method. For example, the standard library has an interface SwingConstants that defines constants NORTH, SOUTH, HORIZONTAL, etc. Any class that implements the java interface SwingContants automatically inherits these constants. His methods can, for example, directly refer to the NORTH constant without resorting to the cumbersome SwingConstants notation. NORTH. However, this use of interfaces considered obsolete and therefore not recommended.

Any class in Java can only have one superclass, but at the same time, any class can implement multiple interfaces, which allows for maximum flexibility define the behavior of the class. For example, Java has a very important interface Cloneable. So if any class implements the Cloneable interface, then to create exact copies of its objects, you can apply the clone() method from the Object class. And if you need not only to create clones of objects of this class but also compare them, then in this class you need to implement both Cloneable and Comparable interfaces as shown below. For separation, the names of the interfaces that set the properties of the classes are a comma.

java Interfaces and Abstract Classes:

Then you may have the following reasonable questions: why developers Java language created an interface mechanism and why not make an interface Comparable with an abstract class, for example, as shown below?

In this case, the Employee class discussed here could simply extend the abstract and implement the compareTo() method like this:

Unfortunately, this would create a lot of problems associated with the use of the abstract base class to express a generic property. After all, every class can only extend one class. Let’s say the Employee class is already a subclass of some other class, say Person. This means that he is no longer can extend another class like this:

But at the same time, each class can implement any number of java interfaces, as shown below.

In other programming languages, and in particular in C ++, classes can have several superclasses. This language facility is called multiple us / eating. The Java creators decided not to support multiple inheritance because it makes the language too complex (like C ++) or less efficient (like Eiffel). At the same time, java interfaces provide most of the benefits of multiple inheritance without complicating the language or reducing its efficiency.

Static and private methods in Java interface:

Starting with Java 8, it is allowed to inject static methods into java interfaces. Formal reasons why static could not be present in the interface methods, nothing existed. But such methods were not consistent with the view interfaces as abstract specifications.

In the past, static methods were often defined in an additional class, accompanying the java interface. In the Java standard library, you can find pairs of interfaces and utility classes like Collection / Collections or Path / Paths. This separation is no longer required.

Consider the Paths class as an example. It has a couple of factory methods to compose a path to a file or directory from a sequence of character lines, for example, like this: Paths.get (“jdkl-11”, “conf”, “security”). As of Java 11, equivalent methods are provided in the Path interface as follows way:

In this case, the need for the Paths class simply disappears. Similarly, implementing own java interfaces, it no longer makes sense to provide a separate companion· The leading class for utility methods.

Since Java 9, methods in an interface can be declared private (private). A private method can be a static or an instance method. BUT since private methods can be used in other methods of the interface itself, then their use is limited to the role of helper methods for other methods of this interface.

Methods with default implementation:

You can provide a default implementation for any java interface method. Such a method should be marked with the default access modifier as shown below.

Of course, there are not very many benefits from this method, since, in each real implementation of the Comparable interface, it will be overridden. But sometimes the methods of the default implementation turns out to be useful. For example, the Iterator interface for accessing the elements of the data structure will be presented. This java interface declares the remove() method:

To implement an iterator, you will need to provide the hasNext() and next() methods. There are no default methods for these methods because they depend on the specific data structure that you want to traverse. But if realizable the iterator is read-only, then the remove() method is generally possible not to worry.

Other methods can be called from methods with a default implementation. For example, in the Collection interface, you can define the service method isEmpty(), as shown below. And then the programmer implementing the Collection interface, you don’t have to worry about implementing this method.

NOTE: Actually the Collection interface from the Java API is nothing does not do that. Instead, it has an abstract class A AbstractCollection, implementing the Collection interface and defining the isEmpty() method in terms of the size() method. Those who implement collections are generally advised to extend the class A AbstractCollection But this method is outdated, since it is enough to implement the corresponding methods in the java interface.

Methods with default implementations play an important role in the future development of java interfaces. Consider the Collection interface as an example, many years included in the Java standard library. Let’s say it was once provided the following class that implements the Collection interface:

and later, starting with Java 8, the method was introduced into this java interface stream().

Let’s also assume that stream() is not the default implementation. In such a case, the Bag class no longer compiles because it does not implement a new method from the Collection interface. Thus, injecting into the java interface of the method with a non-default implementation breaks source compatibility.

But let’s say that this class is not recompiled and just used containing its old archive JAR file. This class is still loaded, despite the missing method. Programs can still build instances of the Bag class, and nothing bad will happen. But if the program does calling the stream() method on an instance of the Bag class, then a type error occurs AbstractMethodError.

This problem can be resolved by declaring the stream() method as default. And then the Bag class will compile again. And if this class is loaded without recompilation and the stream() method is called for an instance of the Bag class, then such a call occurs by reference Collection. stream.

Resolving conflicts with default methods:

What if the same method is first defined by default in the same java interface, and then in the same way in another java interface or as a method in a superclass? Languages ​​such as Scala and C ++ have complex rules for resolving such ambiguities. And in Java, these rules are much simpler and are as follows.

  • In a conflict, the superclass wins. If the superclass provides a specific method, then default methods with the same name and type parameters are simply ignored.
  • Java Interfaces come into conflict. If the superinterface provides a method, and the other java interface is a method (default or otherwise) with the same name and types of parameters, then to resolve the conflict, you must override this method.

Let’s consider the second rule. Let’s say another java interface defines a method getName() as follows:

What happens if you generate the below class that implements both interface?

This class inherits both conflicting getName() methods provided by the Person and Named interfaces. Instead of choosing one of these methods, the Java compiler will give an error message, leaving the programmer himself resolve the resulting ambiguity. To do this, it is enough to provide the method getName() in the Student class and select one of the conflicting methods in it as follows way:

Now let’s say that the Named interface does not provide an implementation of the method getName() by default:

Can Student class inherit default method from java interface Person? At first glance, this may seem quite reasonable, but the Java developers decided to opt for uniformity. Regardless of character conflict between two java interfaces, at least one of them provides an implementation the desired method, and the compiler will give an error message by providing the programmer the ability to resolve the ambiguity that has arisen.

NOTE: If none of the java interfaces provide a default implementation of the generic for them method, then no conflict arises, as, in fact, it was before Java 8. In this case, for a class that implements these interfaces, there are two choices: implement the method or leave it unimplemented and declare the class as a Abstract.

So, we’ve covered conflicts between java interfaces. Now consider a class that extends the superclass and implements the java interface, inheriting from both one and the same method. Let’s say the Student class inherits from the Person class and implements the Named interface is defined as follows:

In this case, only the method from the superclass matters, and any method with the default implementation from the java interface is ignored. In this example, the class Student inherits the getName() method from the Person class, and it doesn’t matter at all for him, whether the Named interface provides the same default method. After all in this case, the first rule mentioned above is observed, according to which in a conflict, the superclass wins.

This rule guarantees compatibility with the Java 7 version. If you introduce methods with the implementation by default to the java interface, this will not affect the operable and application code written before such methods appeared in java interfaces.

Java Interface and callbacks:

Callback is a typical programming pattern. In that, the template specifies the action that should occur where a specific event. Such an event can, for example, occur as a result of a click on an on-screen button or menu item selection in the user interface. But since we have not yet touched on the implementation of user interfaces, then consider a similar but simpler situation.

The javax. swing includes a Timer class with which you can notify about the expiration of a specified period of time. So, if in the part of the program the time is counted down on the clock face, you can organize a notification every second to update the watch face.

When building a timer, a period of time is set and it is indicated that it should be done after a specified period of time. But how to tell the timer what should he do? For this purpose, many programming languages ​​provide the name of the function that the timer should call periodically. But in classes from The Java Standard Library have adopted an object-oriented approach. In particular, an object of some class is passed to the timer, and the timer calls one of the methods for an object of this class. Object passing is considered more flexible than passing functions since the object can carry additional information.

Of course, the timer must know which method to call. Therefore it requires you to specify an object of a class that implements the ActionListener interface from the java package.awt. event, which is declared below. In this way, the timer calls the actionPerformed () method from this java interface after the specified period of time.

Suppose you want to display the message “At the tone, the time is. “(Time by sound signal ….). For this purpose, you can determine a class that implements the ActionListener interface, placing the statements you want execute in the body of the actionPerformed () method as shown below.

Pay attention to the event parameter of type ActionEvent in the method call actionPerformed(). It provides information about the upcoming event, including time of the event. So, as a result of calling event. getWhen() returns time of occurrence of the event, which is counted in milliseconds.

Next, an object of the TimePrinter class is constructed, which is then passed to the constructor class Timer:

The first parameter of the constructor of the Timer class is a time span, which should expire between successive notifications and which measured in milliseconds, and the receiver object as the second parameter events. Finally, the timer is started as follows:

As a result, every second a message similar to the one shown is displayed on the screen.

Example: how to use the timer in java using TimerTask class:


java interface

Comparator interface in java:

As early we discussed how an array of objects is sorted, provided they are instances of classes that implement the interface Comparable. For example, you can sort an array of character strings because the String class implements the Comparable <String> java interface, and the String. compareTo() compares character strings in lexicographic order.

Now let’s say that you want to sort the character strings in order increasing their length, and not in the lexicographic  order. In the String class, you cannot implement the compareTo() method in two different ways. In addition, this class applies to the Java standard library and is not subject to change.

As a way out of this situation, you can use the second option Arrays method. sort(), whose parameters are an array and an instance comparator a class that implements the Comparator interface below.

To compare character strings in length, it is enough to define a class that implements Comparator <String> interface:

To make a comparison, you actually need to get an instance of this class as follows:

Compare this code snippet with the call to words [i]. compareTo (words [j]). Method compare() is called on the comparator object, not on the character string itself.

NOTE: Although an object of type LengthComparator is stateless, the instance still needs to be retrieved in order to call the compare method O, which is not static.

To sort the array, it is enough to pass an object of the LengthComparator type the Arrays method. sort () as follows:

The array is now ordered as [“Shaista”, “XYZ”, “Fawad khan”] or [“XYZ”, “Shaista”, “Fawad khan”].in the  Next, article, I’ll show you how lambda expressions make it easier to use the Comparator interface in java.

Java Interface Programming Examples:

Example1: how to use a simple java interface in programming:


java interface



java interface

Example3: how to use the Default method in java interface:


java interface


Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button