Search⌘ K
AI Features

The Object Orientation in Go

Explore Go's approach to object orientation by understanding how it replaces traditional classes with types and methods. Learn how encapsulation is managed through package scope, inheritance is achieved via type embedding, and polymorphism is realized with interfaces. This lesson helps you grasp Go's unique object-oriented design for scalable, adaptable programming.

Summary on object orientation

Let us summarize what we have seen about object orientation in Golang so far: Go has no classes, but instead, it has loosely coupled types and their methods to implement interfaces. The three important aspects of OO-languages are encapsulation, inheritance, and polymorphism. How are they realized in Go?

  • Encapsulation (data hiding): in contrast to other OO languages where there are four or more access-levels, Go simplifies this to only two levels:
    • package scope: object is only known in its package, it starts with a lowercase letter
    • exported: object is visible outside of its package because it starts with an uppercase letter. A type can only have methods defined in its package.
  • Inheritance: via composition that is embedding of 1 (or more) type(s) with the desired behavior (fields and methods); multiple inheritance is possible through embedding various types.
  • Polymorphism: via interfaces in which a variable of a type can be assigned to a variable of any interface it implements. Types and interfaces are loosely coupled; again, multiple inheritance is possible through implementing various interfaces. Go’s interfaces aren’t a variant on Java or C# interfaces, they’re much more. They are independent and are key to large-scale programming and adaptable, evolutionary design.

So in effect, we can say that Go implements all important object-oriented features.

Challenge yourself

AI Powered
Saved
5 attempts left
Reset

Hey there! I'm Ed, your mentor here to help you apply what you learned in The Way to Go. Here's your question:

In a banking application developed in Go, how would you utilize Go's object-oriented concepts to achieve encapsulation, inheritance, and polymorphism effectively? Describe how these concepts are realized in Go, considering its approach of loosely coupled types, interfaces, and composition. Provide examples illustrating how Go's implementation of these concepts differs from traditional object-oriented languages like Java or C#.

Demonstrate how Go's object-oriented concepts are used in a banking application. Write your answer with appropriate reasoning.

Give it a try!

You have 5 attempts to answer.

Even without classes and inheritance, Go has managed so well to be an object-oriented language. There is a quiz in the next lesson for you to solve.