Search code examples
oopinheritanceprotectednim-lang

What is the equivalent of Java's protected attributes in Nim?


I was playing around with OOP in Nim and when I tried to implement inheritance between two Nim types in different files, I encounter the following problem, when importing a type from other file could not find a way to implement protected attributes.

In the following block of code, it is represented the Java code.

class Vehicle {
  protected String brand = "Ford";        // Vehicle attribute
}

class Car extends Vehicle {
  private String modelName = "Mustang";    // Car attribute
  
   public String getName() {
       return this.brand + " " + this.modelName;
   }
}

class Main {
  public static void main(String[] args) {

    // Create a myCar object
    var myCar = new Car();
    System.out.println(myCar.getName());
  }
}

Is there anything similar to protected attributes in Nim?

Thanks for your time!


Solution

  • There is no equivalency, Nim only has exported and unexported fields. So if you want to access the brand you need to use * on the field. Though you could likely emulate the same logic as protected using the following 'pattern'.

    As such

    # vehicles.nim
    type Vehicle* = object of RootObj # Or ref object if you want runtime polymorphism
        brand*: string
    
    proc init*(vehicle: var Vehicle) =
      vehicle.brand = "Ford"
    
    # main
    import vehicles
    
    type Car = object of Vehicle
      modelName*: string
    
    proc init*(car: var Car) =
      Vehicle(car).init()
      car.modelName = "Mustang"
    
    proc name*(car: Car): string =
      result = car.name
      result.add " "
      result.add car.brand
    
    let car = (var temp = Car(); temp.init(); temp) # Make a constructor to abstract this away I guess
    echo car.name