Junior — Middle
How do the definitions and usage of interfaces differ in Go, Java, and C#?
sobes.tech AI
Answer from AI
Interfaces in Go, Java, and C# share a common goal — to describe a set of methods that a type must implement, but they differ in syntax and usage features.
-
Go:
- Interfaces are defined as a set of methods without explicit implementation.
- A type is considered to implement an interface if it contains all the methods of the interface (implicit implementation).
- Allows flexible composition and dynamic typing.
type Reader interface { Read(p []byte) (n int, err error) } type File struct {} func (f File) Read(p []byte) (int, error) { /*...*/ } // File automatically implements Reader -
Java:
- Interfaces are explicitly declared with the
interfacekeyword. - A class must explicitly declare
implements InterfaceName. - Interfaces can contain methods with implementations (default methods with Java 8).
interface Reader { int read(byte[] p) throws IOException; } class File implements Reader { public int read(byte[] p) { /*...*/ } } - Interfaces are explicitly declared with the
-
C#:
- Similar to Java: interfaces are explicitly declared.
- A class or struct implements an interface via
: InterfaceName. - Supports explicit and implicit implementation of interface methods.
interface IReader { int Read(byte[] buffer); } class File : IReader { public int Read(byte[] buffer) { /*...*/ } }
Key differences:
- Go uses implicit implementation, which simplifies composition and reduces coupling.
- Java and C# require explicit declaration of interface implementation.
- Java and C# support additional features, such as default methods (Java) and explicit implementation (C#).