×

Interface Program in Java

Interface Program in Java

In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in abstract class is only possible when every method of the abstract class is abstract. In Java, using interface we can achieve 100% abstraction. It is because an interface only allows abstract methods. A field of an interface is always public, final, and static. Thus, the following code.

 // ABC is an interface
interface ABC
{
               int no;
               void print();
}
gets converted by the Java compiler into:
// ABC is an interface
interface ABC
{
               public static final int no;
               public abstract void print();
} 

Observe that keywords like public, static, final, and abstract are implicitly added by the Java compiler. An interface defines a contract that implementing class has to obey. This means an implementing class is bound to define all the abstract methods defined in the interface. This way, an interface ensures the behavior of the implementing class. The interface program in Java shows the importance/ usage of the Java interfaces in the programming world.

Interface and Multiple Inheritance

Unlike classes, Interfaces do support multiple inheritance in Java. This is because, in an interface, only abstract methods are allowed. Consider the following example.

FileName: MultipleInheritanceExample.java

 // interface Parent1
interface Parent1
{
    // an abstract method foo()
    void foo();
}
// interface Parent2
interface Parent2
{
    // an abstract method foo()
    void foo();
}
// the class Client implements both the interfaces simultaneously
class Client implements Parent1, Parent2
{
    // defining the method foo()
    // access specifier has to be public
    public void foo()
    {
        System.out.println(" In the method foo … ");
    }
}
public class MultipleInheritanceExample
{
    // driver method
    public static void main(String argvs[])
    {
        // creating a client object
        Client obj = new Client();
        obj.foo(); // invoking method foo
    }
} 

Output:

In the method foo …

Explanation: For interfaces, instead of the keyword extends, keyword implements is used. The class Client implements both the interfaces leading to multiple inheritance. This multiple inheritance never leads to confusion, as the method foo() is not defined in the mentioned interfaces. In classes, multiple inheritance is not supported because methods in the classes are defined, and this definition gives birth to conflict in the inheriting class. One more thing to note here is that except public access specifier, no other access specifier is used in the implementing class. Since all the abstract methods are public in interfaces, the implementing class cannot assign weaker access specifier (rule of inheritance). Therefore, the implementing class is forced to use the public access specifier while defining the abstract methods.

Inheritance in Interfaces

In Java, when a class inherits an interface, it uses the keyword implements (see the above example). However, in case of an interface inheriting another interface, the keyword extends is used. Consider the following example.

FileName: AbstractClassExample.java

 interface findArea
{
    void area();
}
// inteface GeometricalShape inherits the interface findArea
// Thus, the method area() is also the part of the following interface.
interface GeometricalShape extends findArea
{
    void drawShape();
}
class Rectangle implements GeometricalShape
{
    // defining the abstract methods
    public void drawShape()
    {
        System.out.println("Drawing a rectangle");
    }
    public void area()
    {
        System.out.println("Area of a rectangle is l * b");
    }
}
public class InterfaceInheritanceExample
{
    // driver method
    public static void main(String argvs[])
    {
        // creating an object
        Rectangle rect = new Rectangle();
        // invoking methods
        rect.drawShape();
        rect.area();
    }
} 

Output:

 Drawing a rectangle
Area of a rectangle is l * b 

Explanation: The interface GeometricalShape is inheriting the interface findArea. Therefore, the implementing class Rectangle, is forced to define the abstract methods declared in the interfaces GeometricalShape and findArea.

Which one is more compatible to use abstract class or interface?

We have seen an abstract class or an interface; both are applicable for achieving abstraction. It automatically leads to the dilemma of choosing between an abstract class or an interface to achieve abstraction. The choice between an abstract class and interface depends on the scenario. For example, in cricket, there are many types of bowlers. One bowler is a spinner, another is medium paced, while others are fast bowlers. However, every bowler has something in common. Those common things are the number of matches played or the total number of wickets taken. Therefore, in such scenarios, the abstract classes are the better choice than interfaces. All the common features can be defined in an abstract class (an interface never provides the definition), and unique ones like the type of bowling (spin-bowling, fast bowling, etc.) or action of bowling can be declared as the abstract methods.

Consider another scenario where we have to write a program for allrounders in cricket. Since allrounders can do both things: batting and bowling, this is the example of multiple inheritance because allrounders inherit the features of a batsman as well as bowler, and multiple inheritance is only possible with the interface. Therefore, we have to take the help of interfaces in order to write the programs for allrounders in cricket.


Related Topics

PriorityQueue in Java

PriorityQueue in Java A PriorityQueue is a member of the Java Collection Framework and is used when the values are needed to be processed based on priority. Priority queue operates similar to...

8 minutes read.

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

Counting sort in Java

An array's elements are sorted using the counting sort method, which counts how many times each distinct element appears in the array. The count is kept in an auxiliary array,...

3 minutes read.

Method chaining in Java

Method chaining in Java is the act of calling a series of methods one after the other. The sole distinction between it and function Object () constructor chaining is the difference...

3 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Java Integer reverseByte() method

The reverseByte() method of Java Integer class returns the value obtained by reversing the order of the bytes in the 2’s complement binary representation. Syntax public static int reverseByte (int i) Parameters The parameter...

1 minute read.

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will...

4 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

How to add Elements in Array in Java

Consider an array of the size n, in the given size we must add the elements in the given array. In this tutorial we are preferred to learn how to add...

3 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.

How to Reverse a String in Java

How to Reverse a String in Java There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a...

6 minutes read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

Sudoku in Java

Sudoku is a combinatorial-number-placement puzzle with a logic-based approach. The goal of a traditional Sudoku puzzle is to fill in the numbers on a 9 by 9 grid so that...

6 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.