Go Inheritance and Polymorphism: Difference between revisions
Line 12: | Line 12: | ||
==State Inheritance== | ==State Inheritance== | ||
We implement state inheritance by declaring a base <code>struct</code> that contains all the attributes to be shared by inherited types. In this case, in a vehicle hierarchy, the base type is <code>vehicle</code> and it is declared package-private, as it does not need exposure outside the package. | We implement state inheritance by declaring a base <code>struct</code> that contains all the attributes to be shared by inherited types. In this case, in a vehicle hierarchy, the base type is <code>vehicle</code> and it is declared package-private, as it does not need exposure outside the package. It contains fields that are common to all members of the hierarchy, like <code>speed</code>, for example: | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
type ( | type ( |
Revision as of 22:26, 4 August 2024
Internal
Overview
Go does not have formal inheritance at language level. Inheritance can be implemented via a combination of struct field embedding and interfaces. The Inheritance section of this article explains how that is done. Once an implicit inheritance structure is put in place, polymorphism is also available.
Inheritance
In its most generic form, inheritance in programming languages is the capability of declaring class hierarchies. A hierarchy includes generic classes, called superclasses, that are inherited by more specific and specialized classes, called subclasses.
The superclasses declare attributes (state) and behavior that are shared with all their descendants. This is a great capability when it comes to code reusability. The generic state and behavior is declared only once, in superclass, and it does not have to be repeated in subclasses. The subclasses also have the capability to declare state and behavior that is particular to them only, and differentiate them from siblings in the hierarchy. For more general information on inheritance see:
Inheritance as defined above ca be implemented in Go, but without formal support from the language. State inheritance is implemented using struct embedding. Behavior inheritance is implemented using interfaces.
State Inheritance
We implement state inheritance by declaring a base struct
that contains all the attributes to be shared by inherited types. In this case, in a vehicle hierarchy, the base type is vehicle
and it is declared package-private, as it does not need exposure outside the package. It contains fields that are common to all members of the hierarchy, like speed
, for example:
type (
vehicle struct {
}
)
pkg └── transportation ├── vehicle.go ├── car.go └── plane.go
Behavior Inheritance
Overriding
Polymorphism
Polymorphism is available in Go, but it is implemented differently than in other object-oriented languages.
For a generic discussion on polymorphism, see:
Overriding
TO DEPLETE
Read and merge into document: