×

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 Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

Java String valueOf() method

Java String valueOf() method converts different types of values into String. Such as : int to String, long to String, boolean to String, character to String, float to String, double to...

2 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Root exception in java

Java: The main feature of java which is not in C or object oriented programming language is platform independence. Not only the platform independence there are many other features in java...

3 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

XOR Binary Operator in Java

One of the various Bitwise operators in Java is ava XOR. If two boolean operands are given, the XOR (also known as exclusive OR) returns true. When both of the...

4 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Sort Elements by Frequency in Java

To sort the elements in Java by using frequency, we need an input array. We should create a function that sorts the elements in an array by using their frequencies...

3 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Java Instanceof Keyword

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). The type of comparison in java differentiates the...

4 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Java file Reader

File Reader: It is used to read the data from files. This class inherits the properties from Input Stream Reader Class. File Reader is for reading characters from the file. Input Stream: Java.io...

4 minutes read.

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.