Junior — Middle
What is the role of interfaces in object-oriented programming?
sobes.tech AI
Answer from AI
In object-oriented programming (OOP), interfaces play a key role in defining a contract between classes without specifying the concrete implementation. They allow describing a set of methods that a class must implement, providing:
- Abstraction: the interface defines what should be done, without specifying how.
- Polymorphism: objects of different classes can be used through a common interface.
- Flexibility and extensibility: implementations can be changed without altering the code that uses the interface.
In the Go language, interfaces are especially important because they define behavior, not structure. Any type that implements the interface's methods automatically satisfies the interface, which promotes loose coupling and ease of testing.
Example of an interface in Go:
package main
import "fmt"
type Speaker interface {
Speak() string
}
type Dog struct {}
func (d Dog) Speak() string {
return "Woof!"
}
type Cat struct {}
func (c Cat) Speak() string {
return "Meow!"
}
func makeSpeak(s Speaker) {
fmt.Println(s.Speak())
}
func main() {
d := Dog{}
c := Cat{}
makeSpeak(d) // Woof!
makeSpeak(c) // Meow!
}
Thus, interfaces allow writing more modular and maintainable code.