简体   繁体   中英

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

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

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

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

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 (ie 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 :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM