Defining a Class
Classes are blueprints for creating objects. They bundle data (fields)
and functions that operate on that data (methods) into a single unit.
You can define a class using the class keyword.
class Greeter {
data greeting = "Hello"
func sayHi(data name) {
out("${this.greeting}, ${name}!")
}
}
Creating Instances
To create an object (an instance of a class), you call the class like a function. This creates a new instance, and you can then access its methods using dot notation.
# Create an instance of the Greeter class
data myGreeter = Greeter()
# Call a method on the instance
myGreeter.sayHi("World") # Output: Hello, World!
Constructors
A class can have a special method named init, which acts
as a constructor. The init method is automatically called
when you create a new instance, and it's the perfect place to set up
the object's initial state.
class Point {
func init(data x, data y) {
# 'this' refers to the current instance
this.x = x
this.y = y
}
func toString() {
return "Point(${this.x}, ${this.y})"
}
}
# The arguments are passed to the init method
data p = Point(10, 20)
out(p.toString()) # Output: Point(10, 20)
Inheritance
Ry supports inheritance, allowing a class to inherit fields and
methods from a parent class. To create a child class, use the
< symbol. The child class can override parent methods
and can also call them using the super keyword.
class Animal {
func init(data name) {
this.name = name
}
func speak() {
out("${this.name} makes a sound.")
}
}
# Dog inherits from Animal
class Dog childof Animal {
func init(data name, data breed) {
# Call the parent's constructor
parent.init(name)
this.breed = breed
}
func speak() {
# Call the parent's method
super.speak()
out("${this.name} barks.")
}
}
data myDog = Dog("Rex", "Golden Retriever")
myDog.speak()
# Output:
# Rex makes a sound.
# Rex barks.
Static Methods
You can also define methods that belong to the class itself, rather
than to an instance. These are called static methods and are defined
using the static keyword. They are useful for creating
utility functions that are logically grouped with a class.
class Math {
static func add(data a, data b) {
return a + b
}
static func PI() {
return 3.14159
}
}
# Call the static method directly on the class
data sum = Math.add(10, 5)
out("Sum: ${sum}, PI: ${Math.PI()}") # Output: Sum: 15, PI: 3.14159
With classes, you can now model complex data structures. Next, learn how to direct your program's execution with Control Flow.
Next: Control Flow!