Skip to content

Classes, Methods, and Attributes

mfichman edited this page Dec 5, 2012 · 3 revisions

Classes

A simple class definition in Jogo looks like this:

Rocket < Object {
}

The code above defines a class named Rocket. The Rocket < Object syntax simply means that this object is a reference type, and not a value type. Note: The difference between reference and value types is explained later in this tutorial. The Rocket class, as defined above, isn't very interesting; it only has a default constructor which can be called to create a new Rocket:

rocket = Rocket()

Methods

Classes don't get interesting until methods are defined. Here is an example of a method:

Rocket < Object {
    launch() {
        print('Launching!')
    }
}

This code defines a launch method, which can be called on a Rocket object like this:

rocket.launch()

Note that launch must be called using the . syntax with a rocket object to the left of the .. Calling launch() or Rocket::launch() will not work.

Attributes

Attributes are used to store data inside of an object. For example, the following code would allow the mass of each Rocket to be stored:

Rocket < Object {
    mass Float # Mass of the rocket in kilograms
    launch() {
        print('Launching!')
    }
}

To read an attribute from within the class, simple access it like a variable:

Rocket < Object {
   mass Float # Mass of the rocket in kilograms
   launch() {
      print("The rocket's mass is #{mass}")
   }
}

To read an attribute of an object externally, use the . notation:

print("The rocket's mass is " #{rocket.mass}")

Private and immutable

Sometimes you may want to restrict access to a function or an attribute. The private keyword prevents an attribute or function from being used outside of the class. The immutable keyword prevents an attribute from being modified from outside of the class -- but it can still be read. For example:

Rocket < Object {
    mass immutable Float # Mass of the rocket (read-only)
    @init(value Float) {
        mass = value
    }
    launch() private {
        print("Launching!  Mass: #{mass}")
    }
}

main() Int {
    rocket = Rocket(500.0)
    print("Mass: #{rocket.mass}") # OK, because mass is readable
    rocket.mass = 900.0 # Not OK, mass is read-only
    rocket.launch() # Not OK, launch is private
    ret 0
}
Clone this wiki locally