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
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
描述
首先,我们导入了 fmt 包。
然后,我们在 Triangle、Circle、Square 和 Rectangle 名称下定义了一些抽象类,并在其中定义了属性。
接下来,我们定义了一些与这些抽象类相对应的方法。
然后,我们创建了一个包含抽象方法的 Area 接口。
调用函数 main()。
分别将长度、宽度和高度分配给图形以找到它们的面积。
定义一个接口变量 a。
将三角形、正方形、矩形和圆形分配给抽象变量,并在屏幕上打印它们的面积。
广告