本文介绍了当普通班级可以完成相同的工作时,为什么真正需要接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道接口的真正用途.请检查以下代码.

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();
    }
}

在上面的代码中

如果我从类声明中删除实现Animal,代码仍然可以正常工作而没有任何区别.那么接口的实际用途是什么. ?

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

推荐答案

毫无疑问,即使此时没有接口,您的代码也可以工作,但是.实现接口可以使类对其承诺提供的行为变得更加正式.接口在类和外部世界之间形成契约,并且该契约在编译时由编译器强制执行.如果您的类声称要实现一个接口,则在成功编译该类之前,该接口定义的所有方法都必须出现在其源代码中.

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.

例如,如果您有多个动物类,每个动物类都实现Animal,并且以后要更改Animal接口的结构,则可以帮助您更轻松地更改所有动物标本的结构.

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

这篇关于当普通班级可以完成相同的工作时,为什么真正需要接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:36