Skip to content

Nim Objects — Inheritance, Methods, and Object-Oriented Programming

DodaTech Updated 2026-06-29 1 min read

In this tutorial, you will learn about Nim Objects. We cover key concepts, practical examples, and best practices to help you master this topic.

Nim supports object-oriented programming through objects and methods, with compile-time dispatch and optional inheritance.

Objects

type
  Person = object
    name: string
    age: int

var alice = Person(name: "Alice", age: 30)
echo alice.name  # => Alice

# Mutable
var bob = Person(name: "Bob", age: 25)
bob.age = 26

# Inheritance (ref objects)
type
  Animal = ref object of RootObj
    name: string
  Dog = ref object of Animal
    breed: string

let rex = Dog(name: "Rex", breed: "Shepherd")

Methods

type
  Shape = ref object of RootObj
  Circle = ref object of Shape
    radius: float
  Rectangle = ref object of Shape
    w, h: float

method area(s: Shape): float {.base.} =
  raise newException(ValueError, "abstract")

method area(c: Circle): float =
  Pi * c.radius * c.radius

method area(r: Rectangle): float =
  r.w * r.h

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro