From the course: Treating Go as an Object-Oriented Language
Unlock the full course today
Join today to access over 24,900 courses taught by industry experts.
Leveraging composition - Go Tutorial
From the course: Treating Go as an Object-Oriented Language
Leveraging composition
- [Instructor] So, now I want to show you how to leverage composition. In your pets package, let's create a new file called animal. We will create a type animal that is a struct, and we will put a hidden field, so an encapsulated field called lastAte with a time. So, now, let's put a function on our animal. And this is going to look very familiar. We're going to call it feed, and we will pass it food as a string, return a string. We will set a dot last ate equal to time dot now. So, when we're feeding him, we're going to say that he just ate and we will return format dot sprint f. The animal is eating percent s, and we will pass it the food. Now, let's add another method called, is hungry, and this will return a bool and we will simply return time dot now, let me make this an actual bool here, time dot now dot sub, and let's see. My dog eats all the time, no matter how often he ate. So, we will do, what, two seconds, how…
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)
-