Encapsulation inheritance and polymorphism of Golang

Class encapsulation and method binding

  • Golang supports class operations, but there is no class keyword. It uses struct class to simulate classes
  • The function defined in struct needs to be bound externally. The method is bound to the specified class by specifying the data type class in front of the method, which is somewhat similar to the extension function of C#
package main

import "fmt"

// How C + + creates classes
/*
	class Person{
		public:
			string name
			int age

		public:
			Sayhi(){
				...
			}
	}
*/

// Golang creates a person class and binds the Sayhi() method
type Person struct {
	Name string
	Age int
}

// Binding methods outside a class
// By specifying the data type class in front of the method, bind the method to the specified class, which is somewhat similar to the extension function of C#
// The following person data type is a copy of the person object. Modify the member value in person under this function, and the original data type value will not change
// If you want to modify the value of the original data type in the bound function, you can define it through the pointer func (person *Person) Sayhi() {}
func (person Person) Sayhi(){
	// Class, using its own member Name
	fmt.Println("hi, my name is ",person.Name)
}

// The function is bound in the specified class by pointer, and the member value of the original data type can be modified under the function
func (this *Person) SayHello(){
	this.Name = "china"
	fmt.Println("hi, my name is ",this.Name)
}

func main() {
	person := Person{
		Name: "simple",
		Age: 25,
	}
	fmt.Println(person)
	person.Sayhi()

	fmt.Println(person)
	person.SayHello()
}

Class inheritance

  • When we directly include the type of another class in one class and don't write a paragraph name. It defaults to inheritance from another class
  • During inheritance, although no field name is defined, a default field with the same name will be automatically created, so that the parent class can still be operated in the child class, because the field with the same name may appear in the parent class of the child class
package main

import "fmt"

// Define a human being
type Human struct {
	Name   string
	Age    int
	Gender int
}

// Bind a way to say hello to humans
func (this *Human) Sayhi() {
	fmt.Println("hello, my name is ", this.Name, "age is ", this.Age)
}

// Define a student
// Reference the specified class in another class
type Student struct {
	hum    Human		// Nesting of classes
	School string
}

// Define a teacher to inherit Human
type Teacher struct {
	Human					// When we directly include the type of another class in one class and don't write a paragraph name. It defaults to inheritance from another class
	Subject string

}

func main() {
	// Before we learn about class inheritance, let's take a look at class nesting
	strudent := Student{hum: Human{
		Name:   "Simple",
		Age:    24,
		Gender: 1,
	},
		School: "Chengdu No.7 Middle School",
	}
	fmt.Println(strudent)

	// Inheritance class
	teacher := Teacher{}
	teacher.Name = "Miss Chen"
	teacher.Age = 30
	teacher.Subject = "computer"
	fmt.Println(teacher)
	teacher.Sayhi()				// At the same time, the bound methods are inherited

	// When inheriting, although no field name is defined, a default field with the same name will be automatically created
	// This is so that the parent class can still be manipulated in the child class, because the field with the same name may appear in the parent class of the child class
	teacher.Human.Name = "Miss Lin"
	fmt.Println(teacher)
	teacher.Sayhi()				// At the same time, the bound methods are inherited
}

Access rights of class (access modifier)

  • In Golang, permissions are identified by initial case
  • Import - > if the package names are different, only those beginning with uppercase letters can be accessed
  • For members and methods in the class - > only the initial capital can be used in other packages

Polymorphism (via interface)

Use of interfaces

  • In C + +, when implementing the interface, pure virtual functions are used to replace the interface
  • In Golang, there is a special keyword interface to represent the interface
  • interface is not only used to deal with polymorphism, it can receive any data type, similar to void
package main

import "fmt"

// In C + +, when implementing the interface, pure virtual functions are used to replace the interface
// In Golang, there is a special keyword interface to represent the interface
// interface is not only used to deal with polymorphism, it can receive any data type, similar to void
func main() {
	var i, j, k interface{}
	names := []string{"simple", "china"}

	i = names
	fmt.Println("i Represents an array of slices:", i)

	age := 24
	j = age
	fmt.Println("j Representative number:", j)

	str := "hello world"
	k = str
	fmt.Println("k Representative string:", k)

	// In the above code, we only know that k is an interface, but we can't clearly know the data type it represents
	// Judge whether the specified interface is the specified data type through the variable. (data type)
	kval, ok := k.(int)
	if !ok {
		fmt.Println("k no int")
	} else {
		fmt.Println("k yes int,Value is:", kval)
	}

	// The most common method is to set the interface as the parameter of the function, similar to fmt.Println function, func println (a... Interface {}) (n int, err error) {}
	// You can judge the data type entered by the user through switch, and then do corresponding logical processing according to different data types

	// Create a data slice with three interfaces
	array := make([]interface{}, 4)
	array[0] = 1
	array[1] = "hello world"
	array[2] = true
	array[3] = 3.1415

	for _, val := range array{
		// Gets the real data type of the current interface
		switch t := val.(type) {
		case int:
			fmt.Printf("Current data type is int,The content is:%d\n",t)
		case string:
			fmt.Printf("Current data type is string,The content is:%s\n",t)
		case bool:
			fmt.Printf("Current data type is bool,The content is:%v\n",t)				// %v can automatically derive data types
		default:
			fmt.Printf("Is not a reasonable data type")
		}
	}
}

polymorphic

  • Polymorphism in C language requires parent-child inheritance
  • The polymorphism of Golang does not need inheritance, as long as it implements the same interface
  • To implement Golang polymorphism, you need to define an interface
package main

import "fmt"

// Define a flying behavior. Different things that can fly may be different

// Define an interface. Note that the type is interface
type IFly interface {
	// There can be multiple interface functions, but there can only be prototypes, not implementations
	Fly()
}

// Define an eagle class
type Glede struct {
	Name string
}

// Eagle flight function
func (this *Glede) Fly() {
	fmt.Println(this.Name, ":Spread your wings and soar")
}

type Human struct {
	Name string
}

func (this *Human) Fly() {
	fmt.Println(this.Name,":Can't fly")
}

// Realize polymorphism: define a polymorphic general interface, pass in different objects, call methods leading to, and achieve different effects
func DoFly(fly IFly)  {
	fly.Fly()
}

func main() {
	glede := Glede{Name: "eagle"}
	glede.Fly()

	var fly IFly				// Define an interface variable that contains Fly
	fly = &glede				// Assign a value of glede to fly, and the interface needs to use a pointer to assign a value
	fly.Fly()

	human := Human{Name: "human beings"}
	human.Fly()

	fly = &human
	fly.Fly()

	// Implementation of polymorphism
	fmt.Println("***polymorphic***")
	DoFly(&glede)
	DoFly(&human)
}

  • Define an interface, in which the required interfaces are designed, and there can be multiple interfaces
  • Any type that implements this interface can be assigned to this interface to realize polymorphism
  • There is no need for inheritance between multiple classes
  • If interface defines multiple interfaces, the implementation class must implement all functions before assignment

Tags: Go

Posted on Sun, 26 Sep 2021 03:13:52 -0400 by bluestar