×

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

Java.lang.Exception.NoRunnableMethods

In Programming language, the java lang unexpected no precompiled methods error generally refers to a Junit exception that happens whenever Junit is incapable of locate the precompiled test methods. When...

4 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

How to Convert Binary to Decimal in Java

How to Convert Binary to Decimal in Java There are two methods to convert binary to decimal. Using Integer.parseInt() method Using user-defined logic Using Integer.parseInt() method The parseInt() is a static method of...

2 minutes read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 minutes read.

Java Garbage Collection

Java Garbage Collection In Java, unreferenced objects are treated like garbage. The process of reclaiming the unused memory during runtime automatically is known as the Java Garbage Collection.In other words, the...

4 minutes read.

Collections in Java

Collection framework is one of Java's most powerful subsystems. It is a set of classes and interfaces that is all-the-rage technology for superintending objects and a group of objects. In...

6 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 Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

Java Clone Array

We frequently need to copy an array to back up its original components. We have a few unique numbers and strings, including Armstrong numbers, palindrome numbers, and palindrome strings. To...

4 minutes read.

Interfaces and Classes in Strings in Java

CharBuffer: CharBuffer is utilized to implement the CharSequence interface. With the help of the mentioned class, we can allow character buffers to be utilized instead of CharSequences. We can consider the illustration...

4 minutes read.

Leap Year Program in Java

Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other...

2 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

Packages Program in java

Let us know what package is in the Java programming language, and later we will learn about types of packages and how to define a package. How to import Java...

4 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.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.