From the course: Treating Go as an Object-Oriented Language
Unlock this course with a free trial
Join today to access over 25,500 courses taught by industry experts.
Leveraging polymorphism - Go Tutorial
From the course: Treating Go as an Object-Oriented Language
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…
Contents
-
-
-
-
(Locked)
Structs as classes2m 21s
-
(Locked)
Creating a struct5m 16s
-
(Locked)
Encapsulation2m 43s
-
(Locked)
Leveraging encapsulation5m 35s
-
(Locked)
Solution: Struct as class2m 2s
-
(Locked)
Composition1m 36s
-
(Locked)
Leveraging composition4m 11s
-
(Locked)
Polymorphism2m 59s
-
(Locked)
Leveraging polymorphism4m 49s
-
(Locked)
Solution: OOP4m 56s
-
(Locked)
-