问题
I have been wondering the real use of interface. please check the below code.
interface Animal {
public void eat();
public void travel();
}
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
in the above code if i remove implements Animal from class declaration still the code works fine without any difference. So what is the actual use of interface. ?
回答1:
No doubt your code works even without the interface at this moment, but. Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
For example, if you have multiple animal classes, each implementing Animal, if later on you want to change the structure of the Animal interface, it helps you to easier change the structure of all your animal calsses.
Another example, lets say you work on a group object, and the leader tells you and someone else to make some classes based on a structure given by him (the interface), implementing the interface asures that you got all the method names and structures right. If later on the leader decides that the structure of the classes isn't good, he will change the interface, forcing you to change your class.
For more information, read What is an interface or Undersanding interfaces and their Usefullness
回答2:
The purpose of an interface is not to do things but to define what things the class implementing the interface must do. In your case the interface Animal defines what functions can be invoked on an Animal. So any functions/Classes that rely on the Animal interface know what functions will be implemented by the class implementing the interface Animal.
For eg: suppose there is a method that makes the Animal travel , eg :
public void goToDestination(Animal a)
{
a.travel();
}
Now this function can call the function travel on the Object of type implementing Animal without knowing what is the exact type of the object (It can be a MammalInt or it can be a Amphibian etc). This is the power of interfaces. This is only a basic layman explanation of interface you can Google and read more about Interfaces.
来源:https://stackoverflow.com/questions/23646745/why-interface-really-needed-when-normal-class-can-do-the-same-work