← Back to lessons

26 Classes

Intermediate

Classes in cangjie are reference objects. This is one of the crucial differences between a class and a struct in Cangjie as a struct is a value type. Classes can also inherit from another class while this is not possible for structs.

Classes can be defined as seen here. With a constructor which can be name either init, or the name of the class.

Constructors can be overloaded. For more information check the overloading section of the website.

classes.cj
class Rectangle {
    let width: Int64
    let height: Int64
    public init(width: Int64) {
        this.width = width
        this.height = width
    }

    public init(width: Int64, height: Int64) {
        this.width = width
        this.height = height
    }

    public func area() {
        width * height
    }
}

main() {
    let square: Rectangle = Rectangle(5)
    println(square.area())
}

// Output:
// 25