Skip to content

Instantly share code, notes, and snippets.

@iyashjayesh
Created March 28, 2023 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iyashjayesh/6482acdf6894f2e0eeb2d51e4b630216 to your computer and use it in GitHub Desktop.
Save iyashjayesh/6482acdf6894f2e0eeb2d51e4b630216 to your computer and use it in GitHub Desktop.
An example Go program that demonstrates Polymorphism, Encapsulation, Abstraction, and Composition(Inheritance)
package main
import "fmt"
// Encapsulation: defining a private field in a struct
type person struct {
name string
age int
}
// Polymorphism: defining an interface with a method that can be implemented by different types
type shape interface {
area() float64
}
// Go doesn't support inhertiance, but it supports compostion.
// In Go Inheritance is achieved through composition
// Composition (Inheritance): embedding one struct into another
type rectangle struct {
length float64
width float64
}
type circle struct {
radius float64
}
func (r rectangle) area() float64 {
return r.length * r.width
}
func (c circle) area() float64 {
return 3.14 * c.radius * c.radius
}
func printArea(s shape) {
fmt.Println(s.area())
}
func main() {
// Abstraction: using a package to hide implementation details
// creating a new person and setting their name and age
p := person{name: "Alice", age: 30}
// using the circle and rectangle structs to implement the shape interface
c := circle{radius: 5}
r := rectangle{length: 10, width: 5}
// Polymorphism: calling the printArea function with different shapes
printArea(c)
printArea(r)
// Encapsulation: accessing the private fields of a person struct through its public methods
fmt.Println(p.getName(), "is", p.getAge(), "years old")
}
// Encapsulation: defining public methods to set and get private fields of a person struct
func (p *person) setName(name string) {
p.name = name
}
func (p *person) getName() string {
return p.name
}
func (p *person) setAge(age int) {
p.age = age
}
func (p *person) getAge() int {
return p.age
}
// try it -> https://go.dev/play/p/3ShpusSBhqa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment