What is an interface in Java?

Viewed 41984

Just as a counterpoint to this question: what is an interface in Java?

13 Answers

Interface is a contract. A simple example is a Tenant and Landlord which are the two parties and the contract is the Rent Agreement. Rent Agreement contains various clause which Tenants have to follow. Likewise Interface is a contact which contains various method (Declaration) which the Party has to implement (provide method bodies).Here party one is the class which implement the interface and second party is Client and the way to use and interface is having “Reference of Interface” and “Object of Implementing class”: below are 3 components:(Explained with help of example)

Component 1] Interface : The Contract

interface myInterface{

 public void myMethod();

 }

Component 2] Implementing Class : Party number 1

 class myClass implements myInterface {

 @Override

 public void myMethod() {

 System.out.println("in MyMethod");

 }

 }

Component 3] Client code : Party number 2

 Client.java

 public class Client {

 public static void main(String[] args) {

 myInterface mi = new myClass();

 // Reference of Interface = Object of Implementing Class

 mi.myMethod(); // this will print in MyMethod

 }

 }

Interface : System requirement service.

Description : Suppose a client needed some functionality "i.e. JDBC API" interface and some other server Apache , Jetty , WebServer they all provide implements of this. So it bounded requirement document which service provider provided to the user who uses data-connection with these server Apache , Jetty , WebServer .

From the latest definition by Oracle, Interface is:

There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.

For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobile—stop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System) position data and wireless transmission of traffic conditions and use that information to drive the car.

The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group's software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.

[...] An interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.

The most popular usage of interfaces is as APIs (Application Programming Interface) which are common in commercial software products. Typically, a company sells a software package that contains complex methods that another company wants to use in its own software product.

An example could be a package of digital image processing methods that are sold to companies making end-user graphics programs.

The image processing company writes its classes to implement an interface, which it makes public to its customers. The graphics company then invokes the image processing methods using the signatures and return types defined in the interface. While the image processing company's API is made public (to its customers), its implementation of the API is kept as a closely guarded secret—in fact, it may revise the implementation at a later date as long as it continues to implement the original interface that its customers have relied on.

Check out to learn more about interfaces.

In addition to what others have mentioned and by illogical comparison it's a frame work for wrapping methods so they can be stored in variables.

Thus on the fly you can equate the interface variable to be equal to any method or collection of methods atleast in this sense, a good reason you would usually want to do that is to escape repetitive logic that will definitely be an enemy of progress within the half life of your code at any decaying rate, be careful with the scenario below user discretion is advised.

SCENARIO

You have a game with a drawSillyThings() method in a SoulAvenger class, that has to draw some frames or sprites. Now drawSillyThings() has a list of other methods it needs to call in other to draw a metamorphed glorified-soul-ranger after user kills the grim-reaper in level 5k, i.e. drawSillyThings() needs to call either of inviteTheGrimReaper(), drawUpperCut(), drawTotalKO(), drawVictoryAndGlorifiedRanger(), drawDefeatAndMockery(), drawFightRecap() and drawGameOver() whenever the right situations arise during the gaming experience but all these would result in unwanted logic in drawSillyThings() which might slow the game i.e.

public static class SoulAvenger{

        public SoulAvenger(){
             //constructor logic
        }

        private void loadLevel5k(){...}

        private void dontAllowUserWinOnTime(){...}

        private void loadGrimReaperFight(){...}

        private void drawSillyThings(){
            ... //unaccounted game logic
            while(fighting_in_level_5k){
                while(soul_ranger_has_enough_lives){
                    if(game_state=fight)inviteTheGrimReaper();
                    else if(game_state=medium_blows)drawUpperCut();
                    else if(game_state=heavy_blows)drawTotalKO();
                    else if(game_state=lost)drawDefeatAndMockery();
                    else if(game_state=won)drawVictoryAndGlorifiedRanger();
                    else if(game_state=end)drawFightRecap();
                }else drawGameOver();
            }
        }
}

The problem here is the loop-nested boolean checks that have to be performed each time while the soul-ranger is still alive where as you could just have an alternative class which makes sure drawSillyThings() doesn’t need a game_state to be checked each time in order to call the right method but to do that you ‘ld need to kinda store the right method in a variable so that subsequently you can kinda variable = new method and also kinda variable.invoke(). If that wasn’t something have a look

public static class InterfaceTest{

    public interface Method{
        public void invoke();
    }

    public static void main(String[] args){
        //lets create and store a method in a variable shall we
        Method method_variable=new Method(){
            @Override
            public void invoke(){
                //do something        
            }
        };

        //lets call or invoke the method from the variable in order to do something
        method_variable.invoke();

        //lets change the method to do something else
        method_variable=new Method(){
            @Override
            public void invoke(){
                //do something else       
            }
        };

        //lets do something else
        method_variable.invoke();            

     }

}

This was probably what the guys at oracle had discovered was missing from Java several years before rumors of some developers planning a massive protest surfaced on the web but back to the SoulAvenger, as the gameplay occurs you would definitely just want to kinda have a variable be equated to give the right method to be invoked in drawSillyThings() in order to run things in a silly manner therefore

public static class SoulAvenger{

    private interface SillyRunner{
        public void run_things();
    }

    ...//soul avenging variables
    private SillyRunner silly_runner;

    public SoulAvenger(int game_state){
        //logic check is performed once instead of multiple times in a nested loop
        if(game_state=medium_blows){
            silly_runner=new SillyRunner(){
                @Override
                public void run_things(){
                    drawUpperCut();
                }
            };
        }else if(game_state=heavy_blows){
            silly_runner=new SillyRunner(){
                @Override
                public void run_things(){
                    drawTotalKO();
                }
            };
        }else if(game_state=lost){
            silly_runner=new SillyRunner(){
                @Override
                public void run_things(){
                    drawDefeatAndMockery();
                }
            };
        }else if(game_state=won){
            silly_runner=new SillyRunner(){
                @Override
                public void run_things(){
                    drawVictoryAndGlorifiedRanger();
                }
            };
        }else if(game_state=fight){
            silly_runner=new SillyRunner(){
                @Override
                public void run_things(){
                    drawFightRecap();
                }
            };

        }

    }

    private void loadLevel5k(){
        //an event triggered method to change how you run things to load level 5k
        silly_runner=new SillyRunner(){
            @Override
            public void run_things(){
                //level 5k logic
            }
        };
    }

    private void dontAllowUserWinOnTime(){
        //an event triggered method to help user get annoyed and addicted to the game
        silly_runner=new SillyRunner(){
            @Override
            public void run_things(){
                drawDefeatAndMockery();
            }
        };
    }

    private void loadGrimReaperFight(){
        //an event triggered method to send an invitation to the nearest grim-reaper
        silly_runner=new SillyRunner(){
            @Override
            public void run_things(){
                inviteTheGrimReaper();
            }
        };
    }

    private void drawSillyThings(){
        ...//unaccounted game logic
        while(fighting_in_level_5k){
            while(soul_ranger_has_enough_lives){
                silly_runner.run_things();
            }
        }
    }

}

Now the drawSillyThings() doesn’t need to perform any if logic while drawing because as the right events gets triggered the silly_runner gets equated to have its run_things() method invoke a different method thus using a variable to store and invoke a method kinda-ish although in the real gaming world(I actually mean in a console) several threads will work asynchronously to change interface variables to run different piece of code with the same call.

An interface in java is a special type of Abstract class, the Interface provided the 100% Abstraction but since the java introduce new features in java 8 the meaning of whole Interface is change. Interfaces are used to tell what should be done. But due to new features now we give implementations of methods in Interface, that changed the meaning of Interface. In Interface the method is public abstract by default

interface Bird{
        void sound();
         void eat();
        }

Java doesn't provide the multiple inheritances feature mean a class doesn't have two parents, but we extend multiple Interfaces in java.

An interface is a contract between the system and the external environment. More specifically to Java - a contract for a class (for a specific behavior), implemented in a form that resembles a pure abstract class.

Related