Go語言程式建立抽象類
在本文中,我們將學習如何使用 Go 語言程式設計建立抽象類。
抽象類 - 受限的類稱為抽象類,無法從中建立物件。要訪問抽象類,必須從另一個類繼承。
Go 介面缺少欄位,並且禁止在其中定義方法。任何型別都必須實現每個介面方法才能屬於該介面型別。在某些情況下,在 GO 中擁有方法的預設實現和預設欄位很有幫助。在學習如何操作之前,讓我們首先掌握抽象類的先決條件 -
抽象類中應該有預設欄位。
抽象類中應該存在預設方法。
不應該能夠建立抽象類的直接例項。
示例
將介面(抽象介面)和結構體組合在一起(抽象具體型別)。它們可以一起提供抽象類的功能。請參閱下面的程式 -
package main
import "fmt"
// fmt package allows us to print anything on the screen
// Define a new data type "Triangle" and define base and height properties in it
type Triangle struct {
base, height float32
}
// Define a new data type "Square" and assign length as a property to it.
type Square struct {
length float32
}
// Define a new data type "Rectangle" and assign length and width as properties to it
type Rectangle struct {
length, width float32
}
// Define a new data type "Circle" and assign radius as a property to it
type Circle struct {
radius float32
}
// defining a method named area on the struct type Triangle
func (t Triangle) Area() float32 {
// finding the area of the triangle
return 0.5 * t.base * t.height
}
// defining a method named area on the struct type Square
func (l Square) Area() float32 {
// finding the area of the square
return l.length * l.length
}
// defining a method named area on the struct type Rectangle
func (r Rectangle) Area() float32 {
// finding the area of the Rectangle
return r.length * r.width
}
// defining a method named area on the struct type Circle
func (c Circle) Area() float32 {
// finding the area of the circle
return 3.14 * (c.radius * c.radius)
}
// Define an interface that contains the abstract methods
type Area interface {
Area() float32
}
func main() {
// Assigning the values of length, width and height to the properties defined above
t := Triangle{base: 15, height: 25}
s := Square{length: 5}
r := Rectangle{length: 5, width: 10}
c := Circle{radius: 5}
// Define a variable of type interface
var a Area
// Assign to the interface a variable of type "Triangle"
a = t
// printing the area of triangle
fmt.Println("Area of Triangle", a.Area())
// Assign to the interface a variable of type "Square"
a = s
// printing the area of the square
fmt.Println("Area of Square", a.Area())
// Assign to the interface a variable of type "Rectangle"
a = r
// printing the area of the rectangle
fmt.Println("Area of Rectangle", a.Area())
// Assign to the interface a variable of type "Circle"
a = c
// printing the area of the circle
fmt.Println("Area of Circle", a.Area())
}
輸出
Area of Triangle 187.5 Area of Square 25 Area of Rectangle 50 Area of Circle 78.5
描述
首先,我們匯入了 fmt 包。
然後,我們在 Triangle、Circle、Square 和 Rectangle 名稱下定義了一些抽象類,並在其中定義了屬性。
接下來,我們定義了一些與這些抽象類相對應的方法。
然後,我們建立了一個包含抽象方法的 Area 介面。
呼叫函式 main()。
分別將長度、寬度和高度分配給圖形以找到它們的面積。
定義一個介面變數 a。
將三角形、正方形、矩形和圓形分配給抽象變數,並在螢幕上列印它們的面積。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP