本篇文章介紹 Go 實作抽象類別的方法,其中包含 C# 作為一開始解釋目標的語言。

一個抽象類別的範例

抽象類別 Animal

  • 兩個類別,一個抽象類別 Animal;另一個實體類別 Person
  • Animal 有兩個屬性,NameAge
  • Animal 建構子包含兩個屬性的傳入
  • Animal 有一個已實作方法 GetInfo()
  • Animal 有一個未實作方法 SayHello()
1
2
3
4
5
6
7
8
9
10
11
12
abstract class Animal {
protected string Name;
protected int Age;
public abstract void SayHello();
public Animal(string name, int age) {
Name = name;
Age = age;
}
public string GetInfo() {
return "Name: " + Name + ", Age: " + Age;
}
}

實體類別 Person

  • Person 實作 Animal
  • Person 繼承 Animal 的建構子
  • Person 實作 SayHello()
1
2
3
4
5
6
class Person : Animal {
public Person(string name, int age) : base(name, age) { }
public override void SayHello() {
Console.WriteLine("Hello, I am " + this.Name);
}
}

Main()

  • Main() 建構 Person 放進 Animal 型態的變數
  • Main() 使用 Animal 型態的變數,呼叫方法 GetInfo()SayHello()
1
2
3
4
5
public static void Main(string[] args) {
Animal animal = new Person("Tom", 12);
Console.WriteLine(animal.GetInfo()); // Name: Tom, Age: 12
animal.SayHello(); // Hello, I am Tom
}

Go 實作抽象類別

  1. 定義在 Go 的 IAnimal interface

    • Animal 有一個未實作方法 SayHello()
  2. 實作在 Go 的 Animal struct

    • Animal 有兩個屬性,NameAge
    • Animal 有一個已實作方法 GetInfo()
  3. 實作在 Go 的 Person struct

    • Person 擁有 Animal struct
    • Person 實作 SayHello()
  4. 實作在 Go 的 main()

    • main() 建構 Person 放進 Animal 型態的變數
    • main() 使用 Animal 型態的變數,呼叫方法 GetInfo()SayHello()

Go IAnimal interface

定義原抽象類別 Animal 的抽象和實體方法,包含 GetInfo()SayHello()

1
2
3
4
type IAnimal interface {
GetInfo() string
SayHello()
}

Go Animal struct

實作原抽象類別 Animal 屬性和已實作方法

1
2
3
4
5
6
7
8
9
type Animal struct {
Name string
Age int
}

func (a *Animal) GetInfo() string {
age := strconv.Itoa(a.Age)
return "Name: " + a.Name + ", Age: " + age
}

Go Person struct

實作類別 PersonSayHello()

1
2
3
4
5
6
7
type Person struct {
Animal
}

func (p *Person) SayHello() {
fmt.Println("Hello, I am " + p.Name)
}

Go 的 main()

  1. 調用時先定義參數 animal,型態是 interface IAnimal,用以呼叫封裝的方法
  2. 建構 Person 類別,將其記憶體位置給 interface IAnimal
  3. 建構方法包含 new keyword 和 struct literal
  4. 呼叫 interface IAnimal 的方法,其底層呼叫的是實體類別 Person 的方法
1
2
3
4
5
6
7
8
func main() {
var animal IAnimal
animal = &Person{
Animal{Name: "Tom", Age: 12},
}
fmt.Println(animal.GetInfo()) // Name: Tom, Age: 12
animal.SayHello() // Hello, I am Tom
}

補充說明 new keyword

1
2
3
4
var animal IAnimal
person := new(Person)
person.Animal = Animal{Name: "Tom", Age: 12}
animal = person

補充說明 struct literal

1
2
3
4
var animal IAnimal
animal = &Person{
Animal{Name: "Tom", Age: 12},
}