Junior
Milline on tavalise ja abstraktse klassi sarnas ja erinevus?
sobes.tech AI
Vastus AI-lt
Golang does not have the concept of "regular class" and "abstract class" in the way they exist in object-oriented languages like Java or C#.
However, their functionality can be mimicked using structures and interfaces.
Similarities (using structures and interfaces in Golang):
- State (data): A structure can contain fields, like a regular class that stores properties.
- Behavior (methods): Methods can be attached to a structure, defining its behavior, similar to methods of a regular class.
- General contract (for abstract class and interface): An interface in Golang defines a set of methods that any structure "implementing" this interface must provide. This is similar to how an abstract class or interface in other languages sets a contract for inheritors or implementing classes.
Differences (in the context of Golang):
| Feature | "Regular class" (structure with methods) | "Abstract class" (interface + structures) |
|---|---|---|
| Direct creation | An instance of the structure can be created. | An instance of the interface cannot be created directly. |
| Method implementation | All methods attached to the structure have an implementation. | The interface only declares methods, without their implementation. |
| Inheritance | No traditional inheritance. Composition (embedding structures) can be used. | The interface is not inherited but implemented by structures. |
| Implementation obligation | No obligation to implement a specific set of methods, except those attached to the structure. | Any structure that "implements" the Golang interface must provide implementations for all its methods. |
| State (fields) storage | The structure can contain data fields. | The interface does not contain data fields. |
Example of imitation:
// interface mimicking an abstract class
type Shape interface {
Area() float64
Perimeter() float64
}
// structure mimicking a regular class
type Circle struct {
Radius float64
}
// implementation of interface methods for Circle
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
func (c Circle) Perimeter() float64 {
return 2 * 3.14 * c.Radius
}
// Another structure implementing the interface
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}
In this example, Shape acts as a contract (similar to an abstract class or interface in other languages), while Circle and Rectangle are concrete implementations (like regular classes). We can create instances of Circle and Rectangle, but cannot directly instantiate Shape. Both structures must implement the Area() and Perimeter() methods to "fulfill" the Shape interface.