1024programmer Java [Go]Object-oriented in Golang

[Go]Object-oriented in Golang

struct interface can realize object-oriented inheritance, encapsulation, and polymorphism

Demonstration of inheritance:
The Tsh type inherits the People type and uses the methods of the People type

Polymorphic demonstration
Tsh type implements the interface Student and implements the methods defined by the interface

Full code:

package main

 import "fmt"

 //Parent type
 type People struct {
 }

 func (p *People) echo() {
     fmt.Println("taoshihan")
 }

 //Interface
 type Student interface {
     Do()
 }

 //Subtype, implements the interface and inherits the parent type
 type Tsh struct {
     People
 }

 func (t Tsh) Do() {
     fmt.Println("taoshihan do")
 }
 func main() {
     //Demo of inheritance
     t := Tsh{People{}}
     t.echo()
     //Polymorphic demonstration
  var student Student
     student = t
     student.Do()
 }

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/764813

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索