课程: Treating Go as an Object-Oriented Language

今天就学习课程吧!

今天就开通帐号,24,700 门业界名师课程任您挑!

Leveraging polymorphism

Leveraging polymorphism

- [Instructor] So now I'm going to show you how to leverage polymorphism in your code. So I want you to jump back to your IDE and in the pets package, let's create a new go file called pet. Now in here we will create a type pet that is an interface. We'll provide methods such as feed, give attention, and is hungry. Now let's go back into dog. We're going to change new dog to return a pet. Now immediately you will notice we don't get any compilation errors in the IDE and that's because we have fully implemented the interface. So let's go ahead and create a new file called cat. And in here we will do a type cat, which is a struct. For simplicity, we will simply put the same variables on here. So color, breed, and animal. We need to implement a couple methods. The first one is on the struct itself. We need to implement the give attention method, which takes an activity of string. And we will simply return…

内容