duanji5116 2013-08-04 23:13
浏览 77
已采纳

Golang:具有多重继承的接口的意义是什么?

I'm a Java programmer, learning to program in Go. So far I really like the language. A LOT more than Java.

But there's one thing I'm a bit confused about. Java has interfaces because classes can inherit only from one class. Since Go allows multiple inheritance, what's the point of interfaces?

  • 写回答

4条回答 默认 最新

  • doulubashang6936 2013-08-05 03:29
    关注

    Polymorphism

    Interfaces enable functions to have a 'placeholder' parameter which can take different structs as an argument. For example, if structs Man, Woman, Child implement interface Human, then a method with the parameter Human can take any of the structs Man, Woman, Child as an argument. Hence, the interface parameter can 'morph' into any struct passed as an argument as long as it implements all functions defined in the interface.

    This is important because interfaces are the only way of achieving Polymorphism in Go, since it doesn't have inheritance. So if Man 'extended' Human (by having it as an anonymous field), any method that used Human as an argument, would not be able to take Man as an argument.

    My confusion stemmed from the fact that inheritance is also a way of achieving Polymorphism in Java, and I assumed that was the case here as well. I stand corrected!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮