Sobes.tech
Junior — Middle

What common features unite classes and interfaces in object-oriented programming?

sobes.tech AI

Answer from AI

Classes and interfaces in object-oriented programming share several common features:

  • Abstraction: Both allow describing abstract data types, hiding implementation details.
  • Behavior definition: Both classes and interfaces specify a set of methods that must be implemented.
  • Polymorphism: Through classes and interfaces, polymorphic behavior can be implemented, allowing objects of different types to be used uniformly.
  • Typing: Both serve to define types that can be used for declaring variables and function parameters.

In Go, interfaces define a set of methods, but there are no classes as such; however, structures with methods serve the role of classes. Interfaces describe behavior, while structures hold data and implementation.

Example in Go:

// Interface
 type Reader interface {
     Read(p []byte) (n int, err error)
 }

// Structure with a method implementing the interface
 type File struct {}

 func (f File) Read(p []byte) (n int, err error) {
     // implementation
     return 0, nil
 }

 func main() {
     var r Reader = File{}
     r.Read(nil)
 }
What common features unite classes and interfaces in… - sobes.tech