×

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

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

2 minutes read.

Convert Char array to string in java

A collection of characters is referred to as a string. A character array differs from a string in that the string is canceled by the special character "\0." A string...

4 minutes read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Java Regular Expressions

Java Regular Expressions The Java Regex or Regular Expression is an API that defines a pattern for searching or manipulating strings. A regular expression is a pattern that can be as simple as...

8 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 Write File

In this post, we'll examine various Java programming methods for writing into files. Since this class is character-oriented due to how it is used in file handling in Java, it...

4 minutes read.

Java Arrays

An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives. An array is a collection of values which...

2 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

3 minutes read.

ConcurrentSkipListSet in Java

ConcurrentSkipListSet is a class that is a part of collection framework in Java.It has been available since Java version 1.6. ConcurrentSkipListSet  is a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.The...

16 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

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

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

Java Pop

The array, linked list, stack, queue, and other data structures are supported by Java programming. The insertion, deletion, and element searching operations are available for every data structure. And Java...

4 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.