Junior — Middle
Explain the differences between a class and an abstract class in object-oriented programming.
sobes.tech AI
Answer from AI
Go does not have classes and abstract classes in the traditional sense like other object-oriented languages. Instead, it uses structs and interfaces.
Compared to classes and abstract classes:
- Class — a template for creating objects with state and behavior.
- Abstract class — a class that cannot be instantiated directly and can contain both implemented and abstract (unimplemented) methods.
In Go:
- Structs describe data.
- Interfaces describe behavior (a set of methods) that structs should implement.
Thus, an interface in Go can be considered similar to an abstract class, as it defines a contract without implementation.
Example:
// Interface (similar to abstract class)
type Animal interface {
Speak() string
}
// Struct (similar to class)
type Dog struct {}
func (d Dog) Speak() string {
return "Woof!"
}
// Usage:
var a Animal = Dog{}
fmt.Println(a.Speak()) // Outputs: Woof!
Therefore, in Go, there are no direct distinctions between classes and abstract classes; instead, composition through interfaces and structs is used.