Hi everyone,
   consider below code:

    interface i{
      void test();
    }
    class A implements i{
    void test(){//code goes here}
    }
    class B implements i{
    void test(){//code goes here}
    }

    here,we can implement method straightaway in class itself, without using interface like,

    class A{
    void test(){//code goes here}
    }

    why we want to define method in interface and implementing in class?
    what is the use of interface to define method there?

    Kindly Correct if i'm wrong.
    i searched for reason all over the internet, but couldnt find out exact answer.
    Thanks in advance.

Hi Surya55!

interface is used for not only reusability and also shold implement the mandatory fields.

for example if you develop a software for a Hospital.
In operation theater you should check all the safety wears (should weare coat, gloves, sleepers, mask, headcover).

if you forgot any one means you are not allowing into that operation theater, it is common for all hospitals

if you are using this interface

package raj.dcs;

/**
 *
 * @author Android_Raj
 */
public interface Operation {

    public boolean is_weare_coat();

    public boolean is_weare_sleepers();

    public boolean is_weare_mask();

    public boolean is_weare_headcover();

    public boolean is_weare_gloves();

}

for the Hospital of XYZ

package raj.dcs;

/**
 *
 * @author Android_Raj
 */
public class XYZHospital implements Operation {

    @Override
    public boolean is_weare_coat() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public boolean is_weare_sleepers() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public boolean is_weare_mask() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public boolean is_weare_headcover() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public boolean is_weare_gloves() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

You can reuse the same interface for Hospital SS also

package raj.dcs;

/**
 *
 * @author Android_Raj
 */
public class SSHospital implements Operation{

    @Override
    public boolean is_weare_coat() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public boolean is_weare_sleepers() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public boolean is_weare_mask() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public boolean is_weare_headcover() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public boolean is_weare_gloves() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

Have A Happy Day..,

Edited 2 Years Ago by raj.mscking

Think about this example.
The Comparable interface defines a method compareTo that compares two objects so they can be sorted etc. Many classes implement this interface - eg Integer, String etc, and each implementation is different because the way you sort Integers is different from how you sort Strings (etc).
Java has methods to sort arrays and Lists of various kinds. It can sort anything that implements the Comparable interface because it knows it can call compareTo to compare the elements of the array or List. If the array or List contains objects that do not implement Comparable then they can't be sorted.

also, what you'll encounter a lot of times when working on big projects.

the tasks are being split up. the ui is done by seperate people as the back-end, and the analysis, well, God knows who might be doing all of that.

let's say, you have to write the UI. are you going to wait with everything until the back-end has been done? well, good luck. you'll never finish in time.
unfortunately, business requirements change all the times.
let's say you need to have staff, like in raj's example, for a hospital.

do you need to know upfront all the types of jobs there will be there? well, you'll never finish. of course, when some specialist is hired, he'll require new functionality, so you'll need to alter the screens somewhat, but just to log them in?

let's say, that you know all employees must login.

public interface Employee{
  public void logIn();
}

with this little interface, you can code everything you need to login any single type of Employee, without knowing which type employee it'll be, and before all the classes for the employeetypes are even created:

public void logInEmployee(Employee employee){
  employee.logIn();
}

if you now have a class Doctor, which implements Employee, and a class Nurse, which implements Employee, you can call this method by:

Doctor d = getDoctorFromId(doctorId);
logInEmployee(d);
Nurse n = getNurseFromId(nurseId);
logInEmployee(n);
Emloyee e = getEmployeeFromId(employeeId); // you don't know the type
// it might be a nurse, it might be a doctor, but it's definitely an employee
logInEmployee(e);

without the interface, you would need to have a superclass for this. but this might lead to issues, since the superclass might have a different implementation for the method.

for an interface, it is forced that, every implementing class has all the methods (either implemented it itself, or inherited it) of the interface and provides an implementation for them.

which is why here:

public void logInEmployee(Employee employee){
  employee.logIn();
}

you don't need to know which type of Employee 'll be passed, since they all provide an implementation for logIn.

In interfaces you have the method headers. In the classes you implement those methods

If you create a class that implements your interface you give more freedom to whom implements the interface. Consider this example where different classes implement the same method in different ways because they have different characteristics:

public interface Person{
...

public String printProfile();
...

}

public abstract Persons implements Person{
private String name;
private int id;
//constructor goes here
.....
}

public class Chef extends Persons{

private String restaurant;
private String bestDish;
private int michelinStars;

public Chef(String name, int id, String restaurant, 
String bestDish, int michelinStars){

super(name, id);
this.restaurant= restaurant;
//rest of constructor
....

        }
...
public String printProfile(){
    return "Chef " + this.name +" works at " + this.restaurant + " and won " + this.michelinStars;
    }
}

public class TennisPlayer extends Persons{

private String favouritRacket;
private String favouritTennisCourt;
private int timesPerWeek;
private String biggestRival;
private int medals;

//constructor goes here
......


public String printProfile(){
    return "Tennis Player " + this.name +"'s favourit racket is " + this.favouriteRacket + " and loves to play at " + this.favouriteTennisCourt
     + ". Plays "+ this.timesPerWeek + "times per week and consider " + this.biggestRival 
     + " as the biggestRival. Number of medals: " + this.medals;
    }


}



public class Test{

....

public static void main(String [] args){

Chef chef = new Chef(...);

TennisPlayer tennisPlayer = new TennisPlayer(...);


System.out.println(chef.printProfile());
System.out.println(tennisPlayer.printProfile());
  }

 } 

// Both classes must implement the same printProfile() method.
//However as they represent different kind of persons, they implement       //the method in different ways. 


}
}

Edited 2 Years Ago by softDeveloper: changed printProfile from private to public

In language-agnostic terms, an interfaces determines "what" and the implementers determine "how".

For e.g. if you have an interface Moveable with a method move, it tells you "what" is to expected from something which is a moveable viz. the ability to move. As to "how" that can be done, it depends on "who" is moving.

This article has been dead for over six months. Start a new discussion instead.