Golang程序 创建抽象类
在这篇文章中,我们将学习如何使用Golang编程来创建一个抽象类。
抽象类 - 一个受限制的类被称为抽象类,它不能用来创建一个对象,要访问一个抽象类,必须从另一个类继承。
Go接口缺乏字段,禁止在其内部定义方法。任何类型都必须实现每个接口方法,才能属于该接口类型。在有些情况下,在GO中拥有一个方法的默认实现和默认字段是很有帮助的。Let’s first grasp the prerequisites for an abstract class before learning how to do it −
- 抽象类中应该有默认字段。
-
抽象类中应该有默认方法。
-
直接创建一个抽象类的实例是不可能的。
例子
一个接口(抽象接口)和结构体将被结合起来(抽象具体类型)。它们一起可以提供一个抽象类的功能。请看下面的程序–
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包。
-
然后,我们在三角形、圆形、方形和矩形下定义了一些抽象类,并在其中定义了属性。
-
接下来,我们定义了一些与这些抽象类相对应的方法。
-
然后,我们创建了一个包含抽象方法的Area接口。
-
调用函数main()。
-
分别给数字分配长、宽、高,以找到它们的面积。
-
定义一个接口变量a。
-
将三角形、正方形、长方形和圆形分配给这个抽象变量,并在屏幕上打印它们的面积。