What other languages allow programmers to use Interfaces as function parameters?

只谈情不闲聊 提交于 2019-12-11 13:27:27

问题


Let me explain:

I know that, in Java, you can do stuff like this:

int myMethod(Burnable obj){

 /*do stuff that's only applicable if the argument implements the Burnable 
  *interface
  */
}

I like programming in PHP the most, and I'm not sure whether I can do that in PHP too.

Furthermore, I'd like to know what other reasonably mainstream languages that feature this, as in my view it's a way of building modularity into your code.

Thank you


回答1:


All statically-typed languages (C, C++, Java, Objective-C, Ada, and many others) allow one to specify the types of a function's parameters. A subset of them allow for overloading (having multiple different functions with the same name but with different typed parameters). Since PHP5, it is possible to specify the types of parameters using type hinting to validate that function calls pass parameters of the expected type; however, PHP does not support overloading (although you can make functions accept multiple different types, and then check the types and dispatch to different implementations by type).




回答2:


All the standard CLR languages (C#, VB.NET, F#) support using interfaces. Haskell has typeclasses which serve a similar function.




回答3:


Every object-oriented language allows this. They differ in how they spell "interface". In C++ it is just a particular kind of class, where every member is "pure virtual" (now known as "abstract"). In C# it's just like java. In the dynamically-typed languages, PHP, Python, and Ruby for example, it is just implicit (i.e. the interface to which the argument must conform is not spelled out explicitly, but there still is an "interface" in the abstract).

The ability to do this is related to the Liskov substitution principle, and it is one of the fundamental tenets of object-oriented programming. Glad you like it :-)



来源:https://stackoverflow.com/questions/5346393/what-other-languages-allow-programmers-to-use-interfaces-as-function-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!